单链表链栈与顺序栈不太相同的地方就是不需要判断栈是否为满,链栈理论上可以无限延伸。
出栈的时候,将底部也就是头结点后面的第一个结点弹出就可以了
package LinkStack;
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
public class SingleLinkStack {
static Node head;
public static void main(String[] args) {
Node head = new Node(0);
head.next = null;
SingleLinkStack singleLinkStack = new SingleLinkStack();
singleLinkStack.init(head);
Node node1 = new Node(1);
Node node2 = new Node(2);
push(node1);
push(node2);
pop();
pop();
pop();
}
public void init(Node head) {
this.head = head;
}
public static void push(Node node) {
node.next = head.next;
head.next = node;
}
public static void pop() {
if (head.next == null)
System.out.println("null");
else {
System.out.println(head.next.data);
head.next = head.next.next;
}
}
}
运行结果如下
2
1
null