数据结构:栈--计算表达式
生活随笔
收集整理的這篇文章主要介紹了
数据结构:栈--计算表达式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
package com.stack;public class Calculator {public static void main(String[] args){String expression = "5*6+10-100";// 定義兩個棧, 一個是數棧, 一個是操作符棧ArrayStackCal numStack = new ArrayStackCal(10);ArrayStackCal operStack = new ArrayStackCal(10);// 定義需要的相關變量int index = 0;int num1 = 0;int num2 = 0;int oper = 0;int res = 0;char ch = ' ';String chs = "";while(true){// 依次得到express中的每個字符ch = expression.substring(index, index+1).charAt(0);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 = numStack.cal(num1, num2, oper);numStack.push(res);operStack.push(ch);}else{operStack.push(ch);}}else{// 如果為空, 直接入棧operStack.push(ch);}}else{// 如果是數,直接入數棧//numStack.push(ch-48); // 存入整數,而不是字符chs += ch;if(index == expression.length()-1){numStack.push(Integer.parseInt(chs));}else{char temp = expression.substring(index+1, index+2).charAt(0);if(numStack.isOper(temp)){numStack.push(Integer.parseInt(chs));chs = "";}}}index++;if(index==expression.length()){break;}}operStack.listChar();numStack.list();while(!operStack.isEmpty()){oper = operStack.pop();num1 = numStack.pop();num2 = numStack.pop();res = numStack.cal(num1, num2, oper);numStack.push(res);}res = numStack.pop();System.out.println(expression+"="+res);} }// 棧 class ArrayStackCal{private int maxSize; //棧的大小 private int[] stack; // 數組模擬棧private int top = -1;public ArrayStackCal(int maxSize){this.maxSize = maxSize;stack = new int[maxSize];}// 判斷棧滿public boolean isFull(){return top == maxSize - 1;}// 判斷棧空public boolean isEmpty(){return top == -1;}// 查看當前棧頂的值public int peek(){return stack[top];}// 入棧public void push(int value){// 先判斷棧是否已滿if(isFull()){System.out.println("棧已滿");return;}top++;stack[top] = value;}// 出棧public int pop(){if(isEmpty()){System.out.println("棧為空");// 跑出異常throw new RuntimeException("棧空,沒有數據!");}int value = stack[top];top--;return value;}// 遍歷棧public void list(){for(int i=top; i>-1;i--){System.out.printf("stack[%d]=%d\n",i,stack[i]);}}public void listChar(){for(int i=top; i>-1;i--){System.out.printf("stack[%d]=%c\n",i,stack[i]);}}// 返回運算符的優先級,優先級使用數字表示,數字越大,優先級越高// 假設表達式中只有 +,-,*,/public int priority(int 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, 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;}return res;} }?
總結
以上是生活随笔為你收集整理的数据结构:栈--计算表达式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构:栈
- 下一篇: java:基本数据类型