栈实现综合计算器
只是考虑加减乘除的情况下 使用栈完成表达式的计算思路: 1.通过一个index(索引),来遍历表达式 2.如果遍历的是数字,则直接进入数栈 3.如果遍历的是一个符号,则需要分一下几种情况: ?(1)如果当前的符号栈是空的,则符号可直接入栈 ?(2)如果当前的符号栈非空,则需要进行比较,当前操作符的优先级小于或等于栈中的操作符,则需要从数栈中pop出两个数,再从符号栈中pop一个符号,进行运算,将得到的结果再入数栈,当前的符号入符号栈;如果当前操作符的优先级大于符号栈中的操作符,则当前操作符直接入符号栈。 4.当表达式被遍历完毕,就顺序从数栈和符号栈中 pop出相应的数和符号,并进行运算 5.最后在数栈中只有一个数字,就是表达式结果
代码如下,纯纯按照上述思路来完成的代码,代码不是很精炼,很浪费空间,但是很好理解,很适合初学者从理论的理解上升到代码的实现
public class Calculation {
public static void main(String[] args) {
String expretion = "70+120*6-4";
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 (true){
ch = expretion.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{
keepNum += ch;
if (index == expretion.length() - 1){
numStack.push(Integer.parseInt(keepNum));
}else{
if (operStack.isOper(expretion.substring(index+1,index+2).charAt(0))){
numStack.push(Integer.parseInt(keepNum));
keepNum = "";
}
}
}
index++;
if (index >= expretion.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.println("表达式" + expretion + "结果为:" + numStack.pop());
}
}
class ArrayStack2{
private int maxSize;
private int[] stack;
private int 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;
}
public void push(int value){
if (isFull()){
System.out.println("栈中已经满了,不能再放入数据");
return;
}
stack[++top] = value;
}
public int pop(){
if (isEmpty()){
throw new RuntimeException("栈空,没有数据可以出栈");
}
return stack[top--];
}
public void list(){
if (isEmpty()){
System.out.println("栈空,没有数据");
return;
}
for (int i=top;i>=0;i--){
System.out.println("stack[" + i + "]:" + stack[i]);
}
}
public int priority(int oper){
if (oper == '+' || oper == '-'){
return 0;
}else if(oper == '*' || oper == '/'){
return 1;
}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;
}
public int peek(){
return stack[top];
}
}
本篇文章是根据尚硅谷数据结构视频进行总结和代码实现,谢谢尚硅谷大学教会我java知识
|