public class LinkedStackInnerImpl<T> { private class Node { T item; Node next; Node() { this.item = null; this.next = null; } Node(T item, Node next) { this.item = item; this.next = next; } boolean end() { return next == null && item == null; } } 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) { LinkedStackInnerImpl<String> linkedStackInner = new LinkedStackInnerImpl<>(); for (String s : "123 1231 312 qwe ad z cxza sd zcd sdfse r ".split(" ")){ linkedStackInner.push(s); System.out.print(s+" " ); } System.out.println(); while ( linkedStackInner.pop() != null){ System.out.print(linkedStackInner.pop()+" "); } } }
输出:
123 1231 312 qwe ad z cxza sd zcd sdfse r sdfse sd z qwe 1231 null
while ( linkedStackInner.pop() != null){ //pop 已经出栈了
System.out.print(linkedStackInner.pop()+" "); //又出一次
}
每执行一次linkedStackInner.pop()都是出栈一次
每次执行linkedStackInner.pop()就是一次出栈,所以你可以设置个变量来存储这个值,而不是直接再调用一次这个方法