例如:计算'4+3*2-1'
思路:
1.需要遍历字符串,获取每一个字符
2.判断当前字符是一个运算符还是一个数字
3.把数字存放在数字栈中,把运算符放在运算符栈
4.运算符栈:
如果是一个空栈,那么直接运算符入栈
如果运算符栈中已经了其他运算符,需要先对比运算符优先级,
新进来的运算符<=原符号栈栈中运算符,那么需要把原运算符弹栈,数字栈中数字进行弹栈,进行运 算,运算后的结果重新放入数字栈中,新运算符入栈
新运算符优先级>原符号栈中运算符,那么新的符号直接入栈用数组来模拟栈
用数组来模拟栈
public class ArrayStack {
// 栈的大小
private int maxStack;
//用数组模拟栈
private int[] stack;
//表示栈顶所在的位置,默认情况下如果没有数据时,使用-1
private int top = -1;
public ArrayStack(int maxStack) {
this.maxStack = maxStack;
stack = new int[maxStack];
}
// 判断是否已经满栈
public boolean isFull(){
return this.top == this.maxStack-1;
}
//判断栈是否是空栈
public boolean isEmpty(){
return this.top == -1;
}
//压栈
public void push(int val){
if(isFull()){
throw new RuntimeException("此栈已满");
}
top++;
stack[top] = val;
}
//弹栈
public int pop(){
if (isEmpty()){
throw new RuntimeException("空栈,未找到数据");
}
int value = stack[top];
top--;
return value;
}
//查看栈中所有元素
public void list(){
if (isEmpty()){
throw new RuntimeException("空栈,未找到数据");
}
for (int i=0;i
public class TestStack {
public static void main(String[] args) {
String str = "4+3*2-1";
//数字栈
ArrayStack numStack = new ArrayStack(10);
//符号栈
ArrayStack symbolStack = new ArrayStack(10);
int temp1 = 0;//两个数进行计算时的数字1
int temp2 = 0;//两个数进行计算时的数字2
int symbolChar = 0;//两个数进行计算时的符号
int result = 0;//两个数进行计算的结果
int length = str.length();
String values = "";
for (int i=0;i



