数据结构与算法--栈


一、栈是什么?

栈(stack)又名堆栈,它是一种运算受限的线性表。限定仅在表尾进行插入和删除操作的线性表。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。

简单来说我们可以把栈结构理解成枪的弹夹只存在两种行为,即出栈和入栈,先压进弹夹的子弹后打出,后压进弹夹的子弹先打出。
在这里插入图片描述

二、栈结构代码案例

class MyStack{

    private int maxSize;//栈的大小
    private int[] stack;//数组模拟栈
    private int top;//标识栈顶,初始值为-1

    public MyStack(int maxSize){
        this.maxSize = maxSize;
        this.stack = new int[maxSize];
        top = -1;
    }

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

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

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

    //出栈
    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("栈空,没有数据");
        }
        return this.stack[top--];
    }

    //遍历栈
    public void list(){
        if(isEmpty()){
            System.out.println("栈空,没有数据");
            return;
        }

        for(int i = this.top; i >= 0; i--){
            System.out.printf("stack[%d] = %d",i,stack[i]);
        }

    }

}

三、栈结构可以做什么?

我们可以通过栈结构来实现简单的计算器功能
在这里插入图片描述

1、需要两个栈结构,一个是数栈用来保存数字,一个是符号栈用来保存操作符
2、用一个变量index去不断的获取表达式中的每一个字符
3、如果是数字就直接放进数栈
4如果是操作符,则先判断目前符号栈是否为空,如果为空则直接加入符号栈
如果不为空,则要判断当前操作符与栈顶的操作符的优先级
5、如果当前操作符的优先级小于栈顶的操作符,则弹出栈顶的操作符,再从数栈弹出两个数,做运算,再把运算结果入数栈,将当前操作符入符号栈
6、如果当前操作符的优先级大与栈顶的操作符,则直接将当前操作符入符号栈
7、当index遍历完表达式后,则依次弹出一个符号与两个数进行运算,结果入数栈,直到符号栈为空,在数栈中的最后一个结果即为最后的运算结果

代码示例

public class Calculator {
    public static void main(String[] args) {
        String expression = "3+2*6-2";
        MyStack numStack = new MyStack(10);
        MyStack operStack = new MyStack(10);

        int index = 0;
        int num1 = 1;
        int num2 = 1;
        int oper = 0;
        int res = 0;
        char ch = ' ';

        String keyNum = "";

        while (true) {

            ch = expression.substring(index,index+1).charAt(0);
//            System.out.println(ch);
            if(operStack.isOper(ch)){//如果是操作符
//                System.out.println(ch);
                //判断当前操作符栈是否为空
                if(!operStack.isEmpty()){//不为空

                    //判断当前操作符与栈内操作符的优先级
                    if(operStack.priority(ch) <= operStack.priority((char) operStack.peek())){
                        //如果当前操作符优先级小于栈中操作符的优先级
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        oper = operStack.pop();
                        res = numStack.cal(num1,num2, (char) oper);
                        numStack.push(res);
                        operStack.push(ch);

                    }else{//相反,直接入栈
                        operStack.push(ch);
                    }

                }else{//为空,则直接入操作符栈
                    operStack.push(ch);
                }

            }else{//否则是数字
                //"30+2*6-2"
                for (int i = index; i < expression.length(); i++){
                    if (operStack.isOper(expression.charAt(i))){
                        numStack.push(Integer.parseInt(keyNum));
                        keyNum = "";
                        break;
                    }else{
                        keyNum += expression.charAt(i);
                        index = i;
                    }
                }


            }

            index++;
            if(index >= expression.length()){
                numStack.push(Integer.parseInt(keyNum));
                break;
            }
        }


        //当表达式扫描完毕,就顺序的从数栈和符号栈中pop出相应的数和符号,并运算
        while(true) {

            if(operStack.isEmpty()){
                break;
            }

            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            res = numStack.cal(num1,num2, (char) oper);

            numStack.push(res);

        }

        //将数栈的最后数,pop出,就是最终结果
        int result = numStack.pop();
        System.out.printf("表达式 %s = %d",expression,result);

    }
}

class MyStack{

    private int maxSize;//栈的大小
    private int[] stack;//数组模拟栈
    private int top;//标识栈顶,初始值为-1

    public MyStack(int maxSize){
        this.maxSize = maxSize;
        this.stack = new int[maxSize];
        top = -1;
    }

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

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

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

    //出栈
    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("栈空,没有数据");
        }
        return this.stack[top--];
    }

    //遍历栈
    public void list(){
        if(isEmpty()){
            System.out.println("栈空,没有数据");
            return;
        }

        for(int i = this.top; i >= 0; i--){
            System.out.printf("stack[%d] = %d",i,stack[i]);
        }

    }

    //查看栈顶的元素
    public int peek(){
        if(isEmpty()){
            throw  new RuntimeException("栈空,没有数据");
        }
        return this.stack[top];
    }

    //判断操作符的优先级,数字约到,优先级越高
    public int priority(char oper){
        if(oper == '*' || oper == '/'){
            return 1;
        }else if(oper == '+' || oper == '-'){
            return 0;
        }else{
            return -1;//目前表达功能只实现加减乘除
        }
    }

    //判断是否是操作符
    public boolean isOper(char val){
        return val == '+' || val == '-' || val == '*' || val == '/';
    }

    //运算方法
    public int cal(int num1, int num2,char oper){
        int res = 0;//存储运算结果

        switch (oper) {
            case '+':
                res = num1 + num2;
                break;
            case '-':
                res = num2 - num1;
                break;
            case '*':
                res = num1 * num2;
                break;
            case '/':
                res = num2 / num1;
                break;
            default:
                break;
        }
        return res;
    }


}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值