09 数据结构与算法之栈

栈的应用场景

计算表达式:

7 * 2 * 2 + 5 + 3 * 2 - 3 / 2

栈的介绍

  1. 栈的英文 stack
  2. 栈是一个先入后出的有序列表
  3. 栈限制线性表只能在一端进行插入和删除,而允许插入和删除的这一端称为栈顶(top),另一端称为栈底(bottom)。
  4. 先进栈的元素在栈底,后进入的元素在栈顶。

栈的实现思路

  • 因为栈也是一个列表,所以我们使用数组来模拟栈。
  • 定义一个变量为 top,表示栈顶,初始化为 -1\
  • 判断栈空
    return top == -1;
    
  • 判断栈满
    return top == maxSize - 1;
    
  • 入栈
    top++;
    stack[top] = n;
    
  • 出栈
    temp = stack[top];
    top--;
    

代码实现

class ArrayStack {
    private int[] arr;
    private int maxSize;
    private int top = -1;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        arr = 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("栈满,不能入栈");
            return;
        }
        top++;
        arr[top] = num;
    }

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

    //遍历栈
    //遍历时需要从栈顶开始显示数据
    public void list() {
        for(int i = top; i >= 0; i--) {
            System.out.println(arr[i]);
        }
    }
}

测试

public class ArrayStackDemo {
    public static void main(String[] args) {
        //测试 ArrayStack 是否正确
        //先创建一个ArrayStack
        ArrayStack stack = new ArrayStack(4);
        String key = "";
        boolean loop = true;
        Scanner in = new Scanner(System.in);

        while(loop) {
            System.out.println("show");
            System.out.println("exit");
            System.out.println("push");
            System.out.println("pop");

            System.out.println("请输入你的选择:");
            key = in.next();
            switch(key) {
                case "show":
                    stack.list();
                    break;
                case "exit":
                    loop = false;
                    break;
                case "push":
                    System.out.println("请输入一个整数");
                    int num = in.nextInt();
                    stack.push(num);
                    break;
                case "pop":
                    try{
                        System.out.println(stack.pop());
                    } catch(Exception e){
                        e.printStackTrace();
                    }
                default:
                    break;
            }
        }
    }
}

计算器实现(计算中缀表达式)

设计思路:

  • 建立两个栈:数栈和符号栈
  • 遍历表达式,如果是数字,就直接进栈,如果是一个符号,就分如下两种情况:
    - 如果符号栈为空,就直接入栈
    - 如果符号栈栈顶元素优先级大于等于该元素优先级,栈顶元素出栈,数栈中出栈两个元素,做相应运算后,运算结果存到数栈中。重复此操作直到符号栈为空,或符号栈栈顶元素优先级小于该元素优先级。
  • 遍历结束后,符号栈出栈一个元素,数栈出栈两个元素,做相应运算后结果存到数栈中。直到符号栈为空(或数栈中只有一个元素)为止。

代码:

import java.util.HashMap;
import java.util.Stack;

public class Calculator {

    public static void main(String[] args) {
        String expression = "7 * 2 * 2 - 5 + 1 - 5 + 3 - 4";
        System.out.println(calculate(expression));
    }

    //表达式中只有数字、+、-、*、/
    public static int calculate(String expression) {
        Stack<Integer> numStack = new Stack<>();
        Stack<Character> operationStack = new Stack<>();
        StringBuffer sb = new StringBuffer();
        HashMap<Character, Integer> Priority = new HashMap<>();
        Priority.put('+', 1);
        Priority.put('-', 1);
        Priority.put('*', 2);
        Priority.put('/', 2);

        for(int i = 0; i < expression.length(); i++) {
            char cur = expression.charAt(i);
            if(cur == '+' || cur == '-' || cur == '*' || cur == '/') {
                if(sb.length() > 0) {
                    numStack.push(Integer.parseInt(sb.toString().trim()));
                    sb.delete(0, sb.length());
                }
                while(!operationStack.empty() && Priority.get(cur) <= Priority.get(operationStack.peek()) ) {
                    int num1 = numStack.pop();
                    int num2 = numStack.pop();
                    char operation = operationStack.pop();
                    numStack.push(operate(num1, num2, operation));
                }
                operationStack.push(cur);
            } else {
                sb.append(cur);
            }
        }
        if(sb.length() > 0)
            numStack.push(Integer.parseInt(sb.toString().trim()));
        while(!operationStack.empty()) {
            int num1 = numStack.pop();
            int num2 = numStack.pop();
            char operation = operationStack.pop();
            numStack.push(operate(num1, num2, operation));
        }
        return numStack.peek();
    }

    public static int operate(int a, int b, char operation) {
        int result = 0;
        switch(operation) {
            case '+':
                result = b + a;
                break;
            case '-':
                result = b - a;
                break;
            case '*':
                result =  b * a;
                break;
            case '/':
                result =  b / a;
                break;
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值