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。