测试

逝去的月光,黎明的红日
posts - 2, comments - 2, trackbacks - 0, articles - 5

自定义堆栈类

Posted on 2007-10-19 18:46 测试 阅读(864) 评论(0)  编辑  收藏 所属分类: Java,Eclipse
最近一直在用堆栈,可是没有去想过它是怎么实现的,也就看了一下牛人们是怎么实现堆栈的,也就写了个自己的堆栈类,以便加强记忆,

 1public class MyLinkStack {
 2    /**
 3     * 内部类,用以存储用户调用<code>MyLinkStack#push(Object)</code><br>
 4     * 传进来的对象。
 5     */

 6    private static class Node {
 7        /**
 8         * 用户需要堆栈的对象
 9         */

10        Object item;
11        /**
12         * 存储前一个Node对象
13         */

14        Node next;
15        /**
16         * 默认的构造函数
17         *
18         */

19        Node() {
20            this.item = null;
21            this.next = null;
22        }

23        /**
24         * 创建一个新的Node对象,用于存储用户push的数据
25         * 
26         * @param item
27         * @param next
28         */

29        Node(Object item, Node next) {
30            this.item = item;
31            this.next = next;
32        }

33        /**
34         * 是否已经到了堆栈底部
35         * 
36         * @return
37         */

38        boolean end() {
39            return this.item == null && this.next == null;
40        }

41    }

42    /**/
43    private Node top = new Node();
44    /**
45     * 向堆栈中存入数据
46     * 
47     * @param item
48     */

49    public void push(Object item) {
50        top = new Node(item, top);
51    }

52    /**
53     * 取出push中的数据
54     * 
55     * @return
56     */

57    public Object pop() {
58        Object result = top.item;
59        if (!top.end()) {
60            top = top.next;
61        }

62        return result;
63    }

64}

以上的堆栈类是用的链式结构。

只有注册用户登录后才能发表评论。


网站导航: