末端哨兵(end sentinel)
2017-02-28 10:16
1051 查看
末端哨兵(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,说明堆栈已经空了。
相关文章推荐
- redis主从集群搭建及容灾部署(哨兵sentinel)
- Sentinel Redis哨兵模式
- Redis:Sentinel哨兵
- redis的Sentinel模式(哨兵模式)的windows安装
- 【Redis】的哨兵(sentinel)详解
- Redis 集群和 Sentinel 高可用Redis哨兵监听模式
- Redis集群redis主从自动切换Sentinel(哨兵模式)
- redis 哨兵(sentinel)
- 高性能网站架构设计之缓存篇(7)- Redis哨兵sentinel机制用法与说明
- 基于keepalived、redis sentinel的多实例redis集群【1】---路由以及哨兵配置
- redis 4.x 安装哨兵模式 sentinel
- 《Redis设计与实现》学习笔记-Sentinel(哨岗、哨兵)
- 启动哨兵Startup Sentinel(1.5.0.11)汉化版
- Redis学习笔记(四) Redis哨兵(sentinel)
- redis主从集群搭建及容灾部署(哨兵sentinel)
- Redis哨兵(sentinel)
- Redis之十六 Sentinel(哨兵)
- Redis容灾部署哨兵(sentinel)机制配置详解及原理介绍
- Redis sentinel 哨兵模式
- 高性能网站架构设计之缓存篇(8)- Redis哨兵Sentinel的搭建和原理说明