Java 数据结构篇-用链表、数组实现栈
以下是用链表和数组实现栈的示例代码:
链表实现栈:
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
class LinkedListStack {
private ListNode top;
public LinkedListStack() {
top = null;
}
public void push(int x) {
top = new ListNode(x);
top.next = top;
}
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 isEmpty() {
return top == null;
}
}
数组实现栈:
class ArrayStack {
private int[] stack;
private int top;
public ArrayStack(int size) {
stack = new int[size];
top = -1;
}
public void push(int x) {
if (top >= stack.length - 1) {
throw new RuntimeException("栈满");
}
stack[++top] = x;
}
public int pop() {
if (top < 0) {
throw new RuntimeException("栈空");
}
return stack[top--];
}
public int peek() {
if (top < 0) {
throw new RuntimeException("栈空");
}
return stack[top];
}
public boolean isEmpty() {
return top == -1;
}
}
这两个实现都包含了栈的基本操作:入栈(push)、出栈(pop)、查看栈顶元素(peek)和检查栈是否为空(isEmpty)。链表实现栈时,我们使用了循环链表来表示空栈。而数组实现栈时,我们定义了一个top
指针来标识栈顶元素的位置。
评论已关闭