public class LinkedStack<T> {
private static class Node<U>{
U item;
Node<U> next;
Node() {
item = null;
next = null;
}
public 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<>();
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<>();
List<String> list = Arrays.asList("Phasers on stun what what!".split(" "));
list.forEach(s -> lss.push(s));
String s;
while((s = lss.pop()) != null){
System.out.println(s);
}
}
}
what!
what
stun
on
Phasers
内部类Node也是一个泛型,它拥有自己的参数类型
这个例子使用的是一个末端哨兵的模式来判断堆栈何时为空。这个末端哨兵是在构建LinkedList构建的。然后,每调用一次push()方法,就会创建一个Node<T>对象,并将其连接到前一个Node<T>对象。当你调用pop()方法时,总是返回top.item,然后丢弃当前对象,将top转换成下一个Node对象,除非你碰见了末端哨兵,这个时候就不能再移动了,在继续调用pop()方法,只能得到null
当然也可以这么做
public class LinkedStack<T> {
private class Node{
T item;
Node next;
Node() {
item = null;
next = null;
}
public Node(T item, Node next) {
this.item = item;
this.next = next;
}
boolean end(){
return item == null && next == null;
}
}
private Node top = new Node();
public void push(T item){
top = new Node(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<>();
List<String> list = Arrays.asList("Phasers on stun what what!".split(" "));
list.forEach(s -> lss.push(s));
String s;
while((s = lss.pop()) != null){
System.out.println(s);
}
}
}