跳到主要内容

Java程序实现栈数据结构

要理解此示例,您应该具备以下 Java 编程 主题的知识:

示例 1:Java 程序实现栈

// Java 中栈的实现

class Stack {

// 存储栈元素
private int arr[];
// 代表栈顶
private int top;
// 栈的总容量
private int capacity;

// 创建一个栈
Stack(int size) {
// 初始化数组
// 初始化栈变量
arr = new int[size];
capacity = size;
top = -1;
}

// 向栈顶推送元素
public void push(int x) {
if (isFull()) {
System.out.println("栈溢出");

// 终止程序
System.exit(1);
}

// 在栈顶插入元素
System.out.println("插入 " + x);
arr[++top] = x;
}

// 从栈顶弹出元素
public int pop() {

// 如果栈为空
// 没有元素可弹出
if (isEmpty()) {
System.out.println("栈为空");
// 终止程序
System.exit(1);
}

// 从栈顶弹出元素
return arr[top--];
}

// 返回栈的大小
public int getSize() {
return top + 1;
}

// 检查栈是否为空
public Boolean isEmpty() {
return top == -1;
}

// 检查栈是否已满
public Boolean isFull() {
return top == capacity - 1;
}

// 展示栈元素
public void printStack() {
for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + ", ");
}
}

public static void main(String[] args) {
Stack stack = new Stack(5);

stack.push(1);
stack.push(2);
stack.push(3);

System.out.print("栈:");
stack.printStack();

// 从栈中移除元素
stack.pop();
System.out.println("\n弹出后");
stack.printStack();

}
}

输出

插入 1
插入 2
插入 3
栈:1, 2, 3,
弹出后
1, 2,

在上述示例中,我们在 Java 中实现了栈数据结构。

要了解更多,请访问 栈数据结构

示例 2:使用 Stack 类实现栈

Java 提供了内置的 Stack 类,可以用来实现栈。

import java.util.Stack;

class Main {
public static void main(String[] args) {

// 创建 Stack 类的对象
Stack<String> animals= new Stack<>();

// 向栈顶推送元素
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("栈:" + animals);

// 从栈顶弹出元素
animals.pop();
System.out.println("弹出后的栈:" + animals);
}
}

输出

栈:[Dog, Horse, Cat]
弹出后的栈:[Dog, Horse]

在上述示例中,我们使用了 Stack 类在 Java 中实现栈。这里,

  • animals.push() - 将元素插入到栈顶
  • animals.pop() - 从栈顶移除元素

注意,我们在创建栈时使用了尖括号 <String>。这表示该栈是泛型类型的。