末端哨兵(end sentinel)

本文介绍了一种利用末端哨兵简化堆栈空检查的方法。通过在构造LinkedStack时预设一个特殊节点作为末端哨兵,可以方便地判断堆栈是否为空,避免了在pop操作中进行复杂的条件判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

末端哨兵(end sentinel)

public class LinkedStack<T> {

    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;
        }
    }

    //创建一个成员变量来充当栈顶元素,此时top对象里面的成员属性都为空。
    private Node<T> top = new Node<>();

    public void push(T item) {
        //把原有的空top放入新对象中的next,这时item就是top对象里面的item,原有的空top就成了现有的top的next
        top = new Node<>(item, top);
    }

    public T pop() {
        T result = top.item;
        //如果top里面的item和next都为空了,说明当前元素为原有的top元素,也就是栈顶元素
        if (top.end())
            top = top.next;
        return result;
    }

}

这个例子使用了一个末端哨兵(end sentinel)来判断堆栈何时为空。这个末端哨兵是在构造LinkedStack时创建的。然后,每调用一次push()方法,就会创建一个Node对象,并将其链接到前一个Node对象。当你调用pop()方法时,总是返回top.item,然后丢弃当前top所指的Node,并将top转移到下一个Node,除非你已经碰到了末端哨兵,这时候就不再移动top了。如果已经到了末端,客户端程序还继续调用pop()方法,它只能得到null,说明堆栈已经空了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值