public class LinkedStack<T> {
int size;//记录栈的有效长度
private static class Node<U>{ //储存值和指向下一个节点的指针
U value;
Node<U> next;
Node(){
this.next=null;
this.value=null;
}
Node(U value,Node next){
this.value=value;
this.next=next;
}
boolean end(){
return value==null&&next==null;
}
}
private Node<T> top=new Node<>();
public void push(T value){
top=new Node<T>(value,top);
size++;
}
public T pop(){
T result=top.value;
if(!top.end()){
top=top.next;
size--;
}
return result;
}
public int size(){
return size;
}
public static void main(String[] args) {
LinkedStack<String> stack=new LinkedStack<>();
for(String s:"1 2 3 4 5 6 7 8 9".split(" ")){
stack.push(s);
}
String str;
while (!((str=stack.pop()) ==null)){
System.out.print(str+" ");
}
}
}
来试试效果:
9 8 7 6 5 4 3 2 1
Process finished with exit code 0