来自thinking In java 的链式栈简单实现[主要是添加末端哨兵,用于判断栈空]
这个跟LinkedList存入一个多余的header节点是一样的道理
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*链式栈 thinking in java chapter15
* @author gaoxingliang
*/
public class LinkedStack<T> {
private static class Node<T>{
T data;
Node<T> next;
Node(){
data=null;
next=null;
}
Node(T data,Node<T> next){
this.data=data;
this.next=next;
}
boolean hasNext(){
return !(data==null&&next==null);
}
}
private Node<T> top=new Node<T>();
/**
* 压入栈
* @param data
*/
public void push(T data){
top=new Node<T>(data,top);
}
public T pop(){
T result=top.data;
if(top.hasNext()==true){
top=top.next;
}else{
//System.out.println("no node for pop");
}
return result;
}
//test
public static void main(String[] args){
//java version 1.7
LinkedStack<String> stack=new LinkedStack<>();
stack.push("123");
stack.push("456");
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());//null
System.out.println(stack.pop());//null
}
}