Java 常见例子

堆栈是一种线性动态数据结构,遵循后进先出(LIFO)原则。在堆栈中,新元素的添加和元素的删除发生在同一端,这意味着堆栈中最后添加的元素将最先从堆栈中删除。

功能堆栈

  • 它是一个动态数据结构。
  • 它具有动态大小。
  • 它使用动态内存分配。

堆栈的操作

  • isEmpty():检查堆栈是否为空。
  • 大小():返回堆栈的大小。
  • topElement():返回堆栈的顶部元素。
  • Push(x):在堆栈顶部添加一个新元素"x"。因此,堆栈的大小增加 1。
    Java 栈
  • pop():删除栈顶元素。因此,堆栈的大小减少 1。
    Java 栈

堆栈的实现

class CreateStack {
  static final int MAX = 100;
  int top;

  //分配堆栈的最大大小
  int stack[] = new int[MAX];

  CreateStack() {
    top = -1;
  }

  //创建一个方法来检查是否
  //栈是否为空
  void isEmpty() {
    if(top == -1) {
      System.out.println("Stack is empty.");
    } else {
      System.out.println("Stack is not empty.");
    }
  }

  //创建一个返回堆栈大小的方法
  int size() {
     return top+1;
  } 

  //创建添加新元素的方法
  void push(int x){
    if(top == (MAX - 1)){
      System.out.println("Stack size limit reached.");
    } else {
      stack[++top] = x;
      System.out.println(x + " is added into the stack.");
    }
  }

  //创建删除顶部元素的方法
  void pop(){
    if(top < 0){
      System.out.println("Stack is empty.");
    } else {
      int x = stack[top--];
      System.out.println(x + " is deleted from the stack.");
    }
  }  

  //创建一个获取顶部元素的方法
  int topElement() {
    if(top < 0) {
      System.out.println("Stack is empty.");
      return 0;
    } else {
      return stack[top];
    }
  }
}

//测试代码
public class MyClass {
  public static void main(String[] args) {
    CreateStack MyStack = new CreateStack();
    MyStack.push(10);
    MyStack.push(20);
    MyStack.push(30);
    MyStack.push(40);

    MyStack.pop();
    MyStack.isEmpty(); 
  }
} 

上面的代码将给出以下输出:

10 is added into the stack.
20 is added into the stack.
30 is added into the stack.
40 is added into the stack.
40 is deleted from the stack.
Stack is not empty.