如何构造栈java
构造栈的Java实现
在Java中,栈(Stack)是一种遵循后进先出(LIFO)原则的数据结构。以下是几种常见的实现方式:
使用Java内置的Stack类
Java标准库提供了java.util.Stack类,可以直接使用:
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1); // 压栈
stack.push(2);
int top = stack.peek(); // 查看栈顶元素
int popped = stack.pop(); // 弹栈
boolean isEmpty = stack.empty(); // 检查是否为空
}
}
使用LinkedList模拟栈
LinkedList实现了Deque接口,可以作为栈使用:
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<Integer> stack = new LinkedList<>();
stack.push(1); // 压栈
stack.push(2);
int top = stack.peek(); // 查看栈顶元素
int popped = stack.pop(); // 弹栈
boolean isEmpty = stack.isEmpty(); // 检查是否为空
}
}
自定义数组实现栈
如果需要完全控制栈的实现,可以用数组手动实现:
public class ArrayStack {
private int maxSize;
private int[] stackArray;
private int top;
public ArrayStack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void push(int value) {
if (isFull()) {
throw new RuntimeException("Stack is full");
}
stackArray[++top] = value;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return stackArray[top--];
}
public int peek() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return stackArray[top];
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize - 1;
}
}
使用泛型的链表实现栈
更灵活的链表实现,支持泛型:
public class LinkedStack<T> {
private static class Node<T> {
T data;
Node<T> next;
Node(T data) {
this.data = data;
}
}
private Node<T> top;
public void push(T item) {
Node<T> newNode = new Node<>(item);
newNode.next = top;
top = newNode;
}
public T pop() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
T item = top.data;
top = top.next;
return item;
}
public T peek() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return top.data;
}
public boolean isEmpty() {
return top == null;
}
}
线程安全的栈实现
对于多线程环境,可以使用ConcurrentLinkedDeque:

import java.util.concurrent.ConcurrentLinkedDeque;
public class Main {
public static void main(String[] args) {
ConcurrentLinkedDeque<Integer> stack = new ConcurrentLinkedDeque<>();
stack.push(1);
stack.push(2);
int top = stack.peek();
int popped = stack.pop();
}
}
每种实现方式各有优缺点,内置Stack类最简单但性能不如LinkedList,自定义实现最灵活但需要更多代码。根据具体需求选择合适的实现方式。






