实现栈数据结构的 Java 程序

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

示例 1:实现 Stack 的 Java 程序

// Stack implementation in Java

public class Stack {

  // store elements of stack
  private int arr[];
  // represent top of stack
  private int top;
  // total capacity of the stack
  private int capacity;

  // Creating a stack
  Stack(int size) {
    // initialize the array
    // initialize the stack variables
    arr = new int[size];
    capacity = size;
    top = -1;
  }

  // push elements to the top of stack
  public void push(int x) {
    if (isFull()) {
      System.out.println("Stack OverFlow");

      // terminates the program
      System.exit(1);
    }

    // insert element on top of stack
    System.out.println("Inserting " + x);
    arr[++top] = x;
  }

  // pop elements from top of stack
  public int pop() {

    // if stack is empty
    // no element to pop
    if (isEmpty()) {
      System.out.println("STACK EMPTY");
      // terminates the program
      System.exit(1);
    }

    // pop element from top of stack
    return arr[top--];
  }

  // return size of the stack
  public int getSize() {
    return top + 1;
  }

  // check if the stack is empty
  public Boolean isEmpty() {
    return top == -1;
  }

  // check if the stack is full
  public Boolean isFull() {
    return top == capacity - 1;
  }

  // display elements of stack
  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: ");
    stack.printStack();

    // remove element from stack
    stack.pop();
    System.out.println("\nAfter popping out");
    stack.printStack();

  }
}

输出

Inserting 1
Inserting 2
Inserting 3
Stack: 1, 2, 3,
After popping out
1, 2,

在上面的例子中,我们已经用 Java 实现了堆栈数据结构。

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

示例 2:使用 Stack 类实现堆栈

Java 提供了一个 Stack 可用于实现堆栈的构建类。

import java.util.Stack;

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

    // create an object of Stack class
    Stack<String> animals= new Stack<>();

    // push elements to top of stack
    animals.push("Dog");
    animals.push("Horse");
    animals.push("Cat");
    System.out.println("Stack: " + animals);

    // pop element from top of stack
    animals.pop();
    System.out.println("Stack after pop: " + animals);
    }
}

输出

Stack: [Dog, Horse, Cat]
Stack after pop: [Dog, Horse]

在上面的例子中,我们使用了 Stack 类在 Java 中实现了堆栈。这里,

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

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