📅  最后修改于: 2023-12-03 15:02:06.011000             🧑  作者: Mango
堆栈(Stack)是一种线性数据结构,具有后进先出(Last In, First Out)的特点,即最后放入的元素将首先被访问或移除。在Java中,我们可以使用数组或链表来实现堆栈数据结构。
以下是使用数组实现堆栈的Java代码片段:
public class Stack {
private int maxSize; // 堆栈的最大容量
private int top; // 栈顶指针
private int[] stackArray; // 存储元素的数组
public Stack(int size) {
maxSize = size;
top = -1;
stackArray = new int[maxSize];
}
public void push(int value) {
if (top < maxSize - 1) {
stackArray[++top] = value;
} else {
throw new IllegalStateException("Stack is full.");
}
}
public int pop() {
if (top >= 0) {
return stackArray[top--];
} else {
throw new IllegalStateException("Stack is empty.");
}
}
public int peek() {
if (top >= 0) {
return stackArray[top];
} else {
throw new IllegalStateException("Stack is empty.");
}
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize - 1;
}
}
使用示例:
Stack stack = new Stack(5);
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.isEmpty()); // 输出: false
System.out.println(stack.isFull()); // 输出: false
以下是使用链表实现堆栈的Java代码片段:
public class Node {
private int value;
private Node next;
public Node(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public class Stack {
private Node top; // 栈顶节点
public Stack() {
top = null;
}
public void push(int value) {
Node newNode = new Node(value);
newNode.setNext(top);
top = newNode;
}
public int pop() {
if (top != null) {
int value = top.getValue();
top = top.getNext();
return value;
} else {
throw new IllegalStateException("Stack is empty.");
}
}
public int peek() {
if (top != null) {
return top.getValue();
} else {
throw new IllegalStateException("Stack is empty.");
}
}
public boolean isEmpty() {
return top == null;
}
}
使用示例:
Stack stack = new Stack();
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.isEmpty()); // 输出: false
以上代码展示了在Java中如何使用数组和链表实现堆栈数据结构。无论你选择哪种实现方式,堆栈都是一个非常有用的数据结构,它在许多应用程序中都有广泛的应用。