栈(stack)

131 阅读2分钟

栈的介绍

  • 栈是一个==先入后出==(filo-first in last out)的有序列表。
  • 栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表。允许插入和删除的一端,为变化的一端,称为 ==栈顶==(Top),另一端固定的一端,称为==栈底==(bottom)。
  • 根据栈的定义可知,最多放入栈中元素在栈底,最后放入的元素在栈顶,而删除元素刚好相反,最后放入的元素最先删除,最后放入的元素最后删除。

栈的应用场景

  1. 子程序的调用: 在调往子程序前,会先将下个指令的地址存到堆栈中,直到子程序执行完后再讲地址取出,以回到原来的程序中。
  2. 处理递归调用: 和子程序的调用类似,只是除了存储下一个指令的地址外,也将参数、区域变量等数据存入堆栈中。
  3. 表达式的转换【中缀表达式转后缀表达式】与求值
  4. 二叉树的遍历
  5. 图形的深度优先(depth-first)搜索法

数组模拟栈的思路分析

定义一个top来表示栈顶,初始化为-1 入栈操作,当有数据加入到栈时,top++; stack[top] = data; 出栈操作,int value = stack[top]; top--;return value;

栈的基础使用

ArrayStack.java

package top.snailstudy.stack;

public class ArrayStack {
    private int maxSize;//栈的大小
    private int[] stack;//数组
    private int top = -1; //没有数据,初始化为-1 表示没有数据

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    //栈满
    public boolean isFull(){
        return top == maxSize -1;
    }

    //栈空
    public boolean isEmpty(){
        return top == -1;
    }

    //入栈
    public void push(int value){
        if(isFull()){
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = value;
    }

    //出栈
    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("栈空");
        }
        int value = stack[top];
        top--;
        return value;
    }

    //遍历栈,遍历时需要从栈顶开始显示数据
    public void list(){
        if(isEmpty()){
            System.out.println("没有数据");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n",i,stack[i]);
        }
    }

    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(5);
        stack.push(4);
        stack.push(6);
        stack.push(8);
        stack.push(10);
        stack.list();
        int pop = stack.pop();
        System.out.println(pop);
        System.out.printf("=========\n");
        stack.list();
    }
}

输出结果: stack[3]=10 stack[2]=8 stack[1]=6 stack[0]=4 10 ========= stack[2]=8 stack[1]=6 stack[0]=4