Java与数据结构——栈(中缀表达式)

:是一个先入后出的有序链表,是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表。允许插入和删除的一端为变化的一端,称为栈顶,另一端为固定的一端,称为栈底

特点:根据栈的定义可知,最先放入栈中的元素在栈底,最后放入的元素在栈顶;而删除元素刚好相反,最后放入的元素最先删除,最先放入的元素最后删除。 

数组模拟栈:

package stack;

import java.util.Scanner;

public class ArrayStack_Demo {
    public static void main(String[] args) {
        //数组模拟栈的测试
        //创建一个ArrayStack对象表示栈
        ArrayStack stack = new ArrayStack(4);
        String key = "";
        boolean loop = true;//控制菜单是否退出
        Scanner input = new Scanner(System.in);

        while (loop){
            System.out.println("show:显示栈");
            System.out.println("exit:退出栈");
            System.out.println("push:添加数据到栈(入栈)");
            System.out.println("pop:从栈中取出数据(出栈)");
            System.out.print("请输入操作:");
            key = input.next();
            switch (key){
                case "show":
                    stack.show();
                    break;
                case "push":
                    System.out.println("请输入添加的数据:");
                    int value  = input.nextInt();
                    stack.push(value);
                    break;
                case "pop":
                    try {
                        int res = stack.pop();
                        System.out.println("出栈的数据是:" + res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    input.close();
                    loop = false;
                    break;
            }
        }
        System.out.println("程序退出!");
    }
}

//定义一个ArrayStack表示栈
class ArrayStack{
    private int maxSize;//表示栈的大小
    private int[] stack;//数组,用数组模拟栈
    private int top = -1;//top表示栈顶,初始化为-1

    //构造器
    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[maxSize];
    }
    //栈满
    public boolean isFull(){
        return top == maxSize - 1;
    }

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

    //入栈 push
    public void push(int value){
        //判断栈满?
        if (isFull()){
            System.out.println("栈已满,不能进行入栈操作!");
            return;
        }
        top++;
        stack[top] = value;
    }

    //出栈 pop
    public int pop(){
        //判断栈空?
        if (isEmpty()){
            //抛出异常
            throw new RuntimeException("栈已空,不能进行出栈操作!");
        }
        int value = stack[top];
        top--;
        return value;
    }

    //显示栈的情况,遍历栈
    public void show(){
        if (isEmpty()){
            System.out.println("栈空!");
            return;
        }
        int temp = top;
        while (temp >= 0){
            System.out.printf("stack[%d] = %d\n",temp,stack[temp]);
            temp--;
        }
    }
}

链表模拟栈:

package stack;

import java.util.Scanner;

public class LinkedlistStack_Demo {
    public static void main(String[] args) {
        //链表模拟栈的测试
        //创建一个LinkedListStack对象表示栈
        LinkedListStack stack = new LinkedListStack(4);
        String key = "";
        boolean loop = true;//控制菜单是否退出
        Scanner input = new Scanner(System.in);

        while (loop){
            System.out.println("show:显示栈");
            System.out.println("exit:退出栈");
            System.out.println("push:添加数据到栈(入栈)");
            System.out.println("pop:从栈中取出数据(出栈)");
            System.out.print("请输入操作:");
            key = input.next();
            switch (key){
                case "show":
                    stack.show();
                    break;
                case "push":
                    System.out.println("请输入添加的数据:");
                    int value  = input.nextInt();
                    stack.push(value);
                    break;
                case "pop":
                    try {
                        int res = stack.pop();
                        System.out.println("出栈的数据是:" + res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    input.close();
                    loop = false;
                    break;
            }
        }
        System.out.println("程序退出!");
    }
}
class LinkedListStack{
    private int maxSize;
    private SingleLinkedList list;
    private int top = -1;
    public LinkedListStack(int maxSize) {
        this.maxSize = maxSize;
        list = new SingleLinkedList(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++;
        list.update(top+1,value);
    }

    //出栈
    public  int pop(){
        if (isEmpty()){
            throw new RuntimeException("栈空,无法出栈!");
        }
        int value = list.showNode(top+1);
        top--;
        return value;
    }

    //显示栈 栈遍历
    public void show(){
        if (isEmpty()){
            System.out.println("栈空!");
            return;
        }
        int show = top;
        while (show >= 0){
            if (show == 0)
                System.out.print(list.showNode(show+1));
            else
                System.out.print(list.showNode(show+1) + "->");
            show--;
        }
        System.out.println();
    }
}
class SingleLinkedList {

    int maxSize = 0;

    //头节点
    private Node head = new Node(-999999);

    //创建一个单链表
    public SingleLinkedList(int maxSize) {
        this.maxSize = maxSize;
        Node temp = head;
        for (int i = 0; i < maxSize; i++) {
            Node node = new Node(0);
            temp.next = node;
            temp = temp.next;//temp指针后移
        }
    }

    //遍历单链表
    public void list() {
        Node temp = head;
        while (true) {
            if (temp.next == null) {
                break;
            }
            temp = temp.next;//temp指针后移
            System.out.println(temp);
        }
    }

    //修改第n个节点的值为value
    public void update(int n, int value) {

        Node temp = head;
        for (int i = 1; i <= n; i++) {//指针向后移动n次
            temp = temp.next;
        }
        temp.value = value;
    }

    //返回第n个节点的值
    public int showNode(int n) {
        Node temp = head;
        for (int i = 1; i <= n; i++) {//指针向后移动n次
            temp = temp.next;
        }
        return temp.value;
    }


}

class Node{
    int value;
    Node next;
    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                ", next=" + next +
                '}';
    }
}

利用栈计算表达式(中缀表达式)

1.通过一个索引值 index 来遍历表达式;

2.如果扫描值是数字,则直接入数栈;

3.如果扫描值是符号,则分情况讨论:

        3.1 如果当前符号栈为空,则符号直接入符号栈;

        3.2 如果当前符号栈不为空,则进行比较:如果当前操作符的优先级小于或者等于栈中操作符,则从数栈中pop出两个数,再从符号栈中pop出一个符号,进行运算,将得到的结果压入数栈,然后将当前操作符入符号栈;如果当前操作符的优先级大于栈中操作符,则直接入符号栈。

4. 当表达式扫描完毕,则顺序的从数栈和符号栈中pop出相应的数和符号,并运行,将运行结果压入数栈;

5. 最后栈中只有一个数字,这就是表达式计算的结果。

package stack;

public class Calculator {
    public static void main(String[] args) {
        String expression = "7+6*6-2";
        //创建两个栈,一个数栈,一个符号栈
        ArrayStack2 numStack = new ArrayStack2(10);
        ArrayStack2 operStack = new ArrayStack2(10);
        //定义需要的相关变量
        int index = 0;//用于扫描
        int num1 = 0, num2 = 0;
        int oper = 0;
        int res = 0;
        char ch = ' ';//将每次扫描得到的char保存到ch

        //开始while循环的扫描expression
        while (true){
            //依次得到expression的每一个字符
            ch = expression.substring(index,index+1).charAt(0);
            //判断ch是什么,然后进行操作
            if (operStack.isOper(ch)){//如果是运算符
                //判断当前符号栈是否为空
                if (!operStack.isEmpty()){
                    //如果符号栈不为空,则进一步判断优先级
                    if (operStack.priority(ch) <=  operStack.priority(operStack.peek())){
                        //如果当前操作符的优先级小于或者等于栈中操作符
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        oper = operStack.pop();
                        res = operStack.cal(num1,num2,oper);
                        //将计算结果压入数栈
                        numStack.push(res);
                        //将当前操作符压入符号栈
                        operStack.push(ch);
                    }else {
                        //如果当前操作符的优先级大于栈中操作符
                        operStack.push(ch);
                    }
                }else {
                    //如果符号栈为空则直接入栈
                    operStack.push(ch);
                }
            }else {
                //扫描值不是符号即为数,则直接压入数栈
                numStack.push(ch - 48);//扫描值是ASCII码值,需转换为数字
            }
            //让index+1,并判断是否扫描到expression的最后
            index++;
            if (index >= expression.length()){
                break;
            }
        }
        while (true){
            //如果符号栈为空,则计算到最后的结果,数栈中只有一个数字【结果】
            if (operStack.isEmpty()){
                break;
            }
            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            res = operStack.cal(num1,num2,oper);
            numStack.push(res);//每次的计算结果入栈
        }
        //数栈中的最后一个数即为计算结果
        System.out.printf("表达式 %s 的计算结果为:%d",expression,numStack.pop());
    }
}
//先创建一个栈,直接使用前面创建好的
//定义一个ArrayStack2 表示栈,需要扩展功能
// 判断数字 or 操作符? 判断操作符优先级?
class ArrayStack2 {
    private int maxSize;//表示栈的大小
    private int[] stack;//数组,用数组模拟栈
    private int top = -1;//top表示栈顶,初始化为-1

    //构造器
    public ArrayStack2(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[maxSize];
    }

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

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

    //入栈 push
    public void push(int value) {
        //判断栈满?
        if (isFull()) {
            System.out.println("栈已满,不能进行入栈操作!");
            return;
        }
        top++;
        stack[top] = value;
    }
    //返回栈顶元素 peek
    public int peek(){
        return stack[top];
    }
    //出栈 pop
    public int pop() {
        //判断栈空?
        if (isEmpty()) {
            //抛出异常
            throw new RuntimeException("栈已空,不能进行出栈操作!");
        }
        int value = stack[top];
        top--;
        return value;
    }

    //显示栈的情况,遍历栈
    public void show() {
        if (isEmpty()) {
            System.out.println("栈空!");
            return;
        }
        int temp = top;
        while (temp >= 0) {
            System.out.printf("stack[%d] = %d\n", temp, stack[temp]);
            temp--;
        }
    }
    //返回运算符的优先级,优先级提前设定,使用数字表示
    //数字越大,优先级越高
    public int priority(int oper){
        if (oper == '*' || oper == '/'){
            return 1;
        }else if (oper == '+' || oper == '-'){
            return 0;
        }
        else {
            return -1;//假定目前表达式只有+,-,*,/
        }
    }

    //判断是不是运算符
    public boolean isOper(int val){
        return val == '+' || val =='-' || val =='*' || val == '/';
    }

    //计算方法
    public int cal(int num1, int num2, int 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;
    }
}

 

存在的问题: ch 只能处理单个字符,对应单位 数,例如:'4','6','9';但是不能处理多位数字的情况,例如:70,80,90,“80+70*90”,需要进一步改进处理多位数的计算。

改进

else {
                //扫描值不是符号即为数,则直接压入数栈
                //numStack.push(ch - 48);//扫描值是ASCII码值,需转换为数字,存在问题:不能处理多位数
                //分析思路
                //1. 当处理多位数时,不能发现是一个数就立即入栈,因为可能存在多位数的情况
                //2. 在处理数时,需要向expression表达式的index后再看一位,如果是数继续扫描,如果是符号,才让拼接后的数入栈
                //3. 因此需要定义一个字符串变量用于数的拼接

                //处理多位数
                keepNum += ch;
                //如果ch已经是expression的最后一位,则直接入栈
                if (index == expression.length()-1){
                    numStack.push(Integer.parseInt(keepNum));
                }else {
                    //判断下一个字符是不是数字,如果是数字,就继续扫描,如果是运算符则入栈
                    //注意只是看 index 下一位字符,不改变index
                    if (operStack.isOper(expression.substring(index + 1, index + 2).charAt(0))) {
                        //如果后一位是运算符,则入栈
                        numStack.push(Integer.parseInt(keepNum));
                        //入栈后一定要清空 keepNum
                        keepNum = "";
                    }
                }
            }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值