基于链表实现栈
public class MyStack {
private ListNode top;
public MyStack() {
top = null;
}
// 向栈中添加元素
public void push(int x) {
ListNode newNode = new ListNode(x);
newNode.next = top;
top = newNode;
}
// 从栈中移除并返回栈顶元素
public int pop() {
if (top == null) {
throw new RuntimeException("栈为空");
}
int value = top.val;
top = top.next;
return value;
}
// 查看栈顶元素但不移除
public int peek() {
if (top == null) {
throw new RuntimeException("栈为空");
}
return top.val;
}
// 判断栈是否为空
public boolean empty() {
return top == null;
}
}
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop()); // 输出:3
System.out.println(stack.peek()); // 输出:2
System.out.println(stack.empty()); // 输出:false
}