type
status
date
slug
summary
tags
category
icon
password

栈的概念

  1. 栈的英文为(stack)
  1. 栈是一个先入后出(FILO-First In Last Out)的有序列表。
  1. 栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表。允许插入和删除的一端,为变化的一端,称为栈顶(Top),另一端为固定的一端,称为栈底(Bottom)。
  1. 根据栈的定义可知,最先放入栈中元素在栈底,最后放入的元素在栈顶,而删除元素刚好相反,最后放入的元素最先删除,最先放入的元素最后删除
notion image
notion image

栈的应用场景

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

思路讲解

notion image

代码实现

package com.qf.linkedList; import java.util.Scanner; public class StackArray {    public static void main(String[] args) {        StackArray arrayQueue = new StackArray(4);        boolean loop=true;        char sc=' ';        while (loop){            System.out.println("e 跳出循环");            System.out.println("p 入栈");            System.out.println("o 出栈");            System.out.println("s 循环队列");            Scanner systemPut=new Scanner(System.in);            sc=systemPut.next().charAt(0);            switch (sc){                case 'p':                    System.out.println("请输入数据:");                    Scanner addNum=new Scanner(System.in);                    int num = addNum.nextInt();                    arrayQueue.push(num);                    break;                case 'o':                    arrayQueue.pop();                    break;                case 's':                    arrayQueue.show();                    break;                case 'e':                    loop=false;                    break;                default :                    break;           }       }   }    public int maxSize;    public int top;    public int [] stack;    //初始化    public StackArray(int maxSize){        this.maxSize=maxSize;        this.top=-1;        this.stack=new int[maxSize];   }    //栈是否已满    public boolean isFull(){        return top==maxSize-1;   }    //栈是否为空    public boolean isEmpty(){        return top==-1;   }    //入栈    public void push(int num){        if (isFull()){            System.out.println("栈已满,请出栈~~~");       }else{            top++;            stack[top]=num;       }   }    //出栈    public int pop(){        if (isEmpty()){            throw new RuntimeException("栈为空,请入栈~~~");       }        int value=stack[top];        top--;        System.out.println("出栈的值为:"+value);        return value;   }    //循环栈元素    public void show(){        if (isEmpty()){            throw new RuntimeException("栈为空,请入栈~~~");       }        for (int i = top; i >=0 ; i--) {            System.out.println("a["+i+"]"+"="+stack[i]);       }   } }
如有不正确的,还请指出!!!
 
顺序存储二叉树数组实现环形队列 详细讲解