public class LinkedStack<T> {
//内部的节点类,它 包含两个区域
//item存放 内容,next存放下前一个节点的指针
private 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);
}
}
//先初始化一个开始节点
private Node<T> top = new Node<T>();
//将内容放到节点
public 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;
}
public static void main(String[] args) {
LinkedStack<String> lss = new LinkedStack<String>();
for(String s : "Phasers on stun!".split(" ")){
lss.push(s);
}
String s ;
while((s = lss.pop()) != null){
System.out.println(s);
}
}
}
备注来之:thinking in java 4th