链表容易报空指针异常的数据结构,但是它也有自己的好处,这里面不用判断栈是否已满,因为相对于数组来讲,链表是一种动态的存储方法,只需要在输出的时候判断是否为空即可.
package Stack;
public class ListStackDemo {
public static void main(String[] args) {
ListStack listStack = new ListStack();
listStack.push(5);
listStack.push(6);
listStack.push(9);
System.out.println("出栈前");
listStack.list();
System.out.println("出栈后");
listStack.pop();
listStack.pop();
listStack.list();
}
}
class ListStack{
Node head=new Node(0);
Node temp=head;
public boolean isEmpty(){
return head.next==null;
}
public void push(int value){
Node node=new Node(value);
temp.next=node;
temp=temp.next;
}
public int pop(){
if (isEmpty()){
throw new RuntimeException("栈空");
}
Node pre=head;
while (true){
if (pre.next==temp){
break;
}
pre=pre.next;
}
pre.next=temp.next;
int value=temp.no;
temp=pre;
return value;
}
public void list(){
Node temp=head;
if(isEmpty()){
System.out.println("栈空");
return;
}
while(true){
if (temp.next==null){
break;
}
System.out.println(temp.next.no);
temp=temp.next;
}
}
}
class Node{
public int no;
public Node next;
public Node(int no) {
this.no = no;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
", next=" + next +
'}';
}
}