使用单链表模拟栈的一下操作的java代码。
public class LinkedListStackDemo {
public static void main(String[] args) {
Node node1 = new Node(2);
Node node2 = new Node(4);
Node node3 = new Node(6);
Node node4 = new Node(8);
SingleLinkedListStack stack = new SingleLinkedListStack();
System.out.println(stack.isEmpty());
stack.push(node1);
stack.push(node2);
stack.push(node3);
stack.push(node4);
stack.pop();
stack.list();
}
}
class SingleLinkedListStack {
private Node top = new Node(-1);
public boolean isEmpty() {
return top.next == null;
}
public void push(Node node) {
//头插法
Node temp = top.next;
top.next = node;
node.next = temp;
}
//出栈
public void pop() {
//先判断是否为空
if(top.next == null) {
System.out.println("栈为空");
return;
}
//然后出栈
int value = top.next.data;
System.out.printf("出栈元素为 %d \n", value);
top.next = top.next.next;
}
public void list() {
//先判断栈是否为空
if(isEmpty()) {
System.out.println("栈为空");
return;
}
while(top.next != null) {
System.out.println(top.next.data);
//后移
top = top.next;
}
}
}
//定义Node,每个Node对象就是一个节点
class Node {
public int data; //存放节点
public Node next;//指向下一个节点
//构造器
public Node(int data) {
this.data = data;
}
}