栈的应用
对输入字符串形式的计算表达式的结果计算
思路:
- 使用栈进行操作
- 对输入的字符串进行依次切割
- 判断得到的字符是数字还是运算符
- 如果为运算符则需要判断运算符的优先性
- 乘除高于加减
- 如果发现当前的符号栈为 空,就直接入栈
- 如果符号栈有操作符,就进行比较,如果当前的操作符的优先级小于或者等于栈中的操作符, 就需要从数栈中pop出两个数,在从符号栈中pop出一个符号,进行运算,将得到结果,入数栈,然后将当前的操作符入符号栈, 如果当前的操作符的优先级大于栈中的操作符, 就直接入符号栈
- 当表达式扫描完毕,就顺序的从 数栈和符号栈中pop出相应的数和符号,并运行
- 最后在数栈只有一个数字,就是表达式的结果
实现代码
package online.zcc815.stack;
public class Calculator {
public static void main(String[] args) throws Exception {
String express = "3+2*6-2";
StackDemoTest numStack = new StackDemoTest(10);
StackDemoTest operator = new StackDemoTest(10);
int index = 0;
int num1 = 0;
int num2 = 0;
int oper = 0;
int result = 0;
char val = ' ';
while (index < express.length()) {
val = express.substring(index, index + 1).charAt(0);
if (operator.isOperator(val)) {
if (!operator.isNull()) {
int peek = operator.getPeek();
if (operator.getPriority(val) <= operator.getPriority(operator.getPeek())) {
num1 = numStack.pop();
num2 = numStack.pop();
oper = operator.pop();
result = numStack.getResult(num1, num2, oper);
numStack.push(result);
operator.push(val);
}else {
operator.push(val);
}
} else {
operator.push(val);
}
} else {
numStack.push(val - 48);
}
index++;
}
while (true) {
if (operator.isNull()) {
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operator.pop();
result = numStack.getResult(num1, num2, oper);
numStack.push(result);
}
System.out.printf("表达式%s = %d", express, result);
}
}
class StackDemoTest {
private int maxSize;
private int[] stack;
private int top = -1;
public StackDemoTest() {
}
public StackDemoTest(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
public int getPeek() {
return stack[top];
}
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
public int[] getStack() {
return stack;
}
public void setStack(int[] stack) {
this.stack = stack;
}
public boolean isNull() {
return top == -1;
}
public boolean isFull() {
return maxSize == top + 1;
}
public void push(int value) {
if (isFull()) {
System.out.println("栈已经满了");
return;
}
stack[top + 1] = value;
top++;
}
public int pop() throws Exception {
if (isNull()) {
throw new Exception("栈已经空");
}
top--;
return stack[top + 1];
}
public void printStack() throws Exception {
if (isNull()) {
throw new Exception("栈已经空");
}
for (int i = top; i >= 0; i--) {
System.out.println(stack[i]);
}
}
public int getPriority(int operator) {
if (operator == '*' || operator == '/') {
return 1;
} else if (operator == '+' || operator == '-') {
return 0;
} else {
return -1;
}
}
public boolean isOperator(char val) {
return val == '*' || val == '/' || val == '+' || val == '-';
}
public int getResult(int num1, int num2, int operator) {
int result = 0;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num2 - num1;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num2 / num1;
break;
default:
break;
}
return result;
}
}