//链表实现栈
public class Stack {
LinkNode head = null;
public void insert(int value) {
LinkNode newNode = new LinkNode(value);
if (head == null) {
head = newNode;
return;
}
LinkNode indexNode = head;
newNode.setNext(indexNode);
head = newNode;
}
public void get() {
if (head != null) {
System.out.println(head.getData());
head = head.getNext();
} else {
System.out.println("栈空");
}
}
public static void main(String[] args) {
Stack node = new Stack();
node.insert(1);
node.insert(2);
node.insert(3);
node.insert(4);
node.insert(5);
node.get();
node.get();
node.get();
node.get();
node.get();
node.get();
}
}
LinkNode 类如下
public class LinkNode {
private int data;
private LinkNode next;
public LinkNode() {
}
public LinkNode(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public LinkNode getNext() {
return next;
}
public void setNext(LinkNode next) {
this.next = next;
}
}