Java的一个堆栈例子

package generics;
/**
 * 堆栈类
 * 栈遵循先入后出规则
 */
public class LinkedStack<T> {

    private Node<T> top = new Node<T>();

    public static void main(String[] args) {

        LinkedStack<String> lss = new LinkedStack<String>();
        for (String s : "Phases on stun !".split(" "))
            lss.push(s);// 压栈
        String str;
        while ((str = lss.pop()) != null)
            System.out.println(str);
    }

    private static class Node<U> {
        U item;
        Node<U> next;

        Node() {
            item = null;
            next = null;
        }

        Node(U item, Node<U> next) {
            this.item = item;
            this.next = next;
        }

        /**
         * 判断是否是空栈
         */
        boolean end() {
            return item == null && next == null;
        }
    }

    /**
     * 压栈新的元素item 新的元素位置指针指向上一次入栈元素
     * 
     * @param item
     *            入栈的新元素
     */
    private void push(T item) {
        top = new Node<T>(item, top);
    }

    /**
     * 出栈 
     * 如果是栈底,返回当前栈的元素 如果还没到栈底,返回下一个栈元素引用
     */
    public T pop() {
        T result = top.item;
        if (!top.end())
            top = top.next;
        return result;
    }

}

输出
!
stun
on
Phases

分析

这个例子使用了一个末端哨兵来判断堆栈何时为空。这个末端
哨兵是在构造LinkedStack时候创建的。然后每调用pop()方法都会返回top.item,然后丢弃当前top所指的Node,并将top移到下一个Node,但是到了末端哨兵就不再移动top了。如果到了哨兵末端继续调用pop,会得到null。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值