package com.dai.stack;
public class Calculator {
public static void main(String[] args) {
//完成表达式的运算
String expression = "103+2*6-6-6";
//创建数栈和符号栈
ArrayStack2 numStack = new ArrayStack2(10);
ArrayStack2 operStack = new ArrayStack2(10);
int index = 0;
int num1 = 0;
int num2 = 0;
int oper = 0;
int res = 0;
char ch = ' ';
String keepNum = ""; //拼接多位数
//开始用while循环扫描expression
while(true) {
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 = numStack.cal(num1, num2, oper);
//运算结果入数栈
numStack.push(res);
//当前操作符入符号栈
operStack.push(ch);
}
else {
operStack.push(ch);
}
}else {
operStack.push(ch);
}
}
else {
//处理多位数时,不能直接入栈,向右看一位是否为符号
keepNum += ch;
if(index == expression.length()-1) {
numStack.push(Integer.parseInt(keepNum));
}else {
if(operStack.isOper(expression.substring(index+1, index+2).charAt(0))) {
numStack.push(Integer.parseInt(keepNum));
keepNum = "";
}
}
}
//index +1 是否扫描到最后
index++;
if(index>=expression.length()) {
break;
}
}
while(true) {
//如果符号栈为空,则计算到最后的结果,数栈中只有一个数字
if(operStack.isEmpty()) {
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
}
System.out.printf("表达式%s = %d\n", expression, numStack.pop());
}
}
//先创建一个栈
class ArrayStack2{
private int maxSzie;
private int[] stack; //数组模拟栈,数据放在这
private int top = -1; //表示栈顶,初始化为-1
public ArrayStack2(int maxSize) {
this.maxSzie = maxSize;
stack = new int[this.maxSzie];
}
//栈满
public boolean isFull() {
return top==maxSzie-1;
}
//栈空
public boolean isEmpty() {
return top == -1;
}
//入栈 - push
public void push(int value) {
if(isFull()) {
System.out.println("栈满了");
return;
}
top++;
stack[top] = value;
}
//出栈
public int pop() {
if(isEmpty()) {
throw new RuntimeException("栈空,无数据");
}
int value = stack[top];
top--;
return value;
}
//返回栈顶元素
public int peek() {
return stack[top];
}
//遍历栈,遍历时需要从栈顶开始显示数据
public void list() {
if(isEmpty()) {
System.out.println("栈空,没有数据");
return;
}
for(int i=top; i>=0; i--) {
System.out.printf("stack[%d] = %d\n", i, stack[i]);
}
}
//优先级
public int priority(int oper) {
if(oper=='*'||oper=='/')
return 1;
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;
default:
break;
}
return res;
}
}