一、基本介绍
二、应用实例
package stack;
public class InffixExpression {
public static void main(String[] args) {
String inffixExpression = "7*2*2-5+1-5+3-4";
InffixStack numStack = new InffixStack(16);
InffixStack operStack = new InffixStack(16);
int index = 0;
int num1 = 0;
int num2 = 0;
int res = 0;
int op = 0;
char ch = ' ';
String numStr = "";
while (true) {
// 取出字符串里的每一个字符
ch = inffixExpression.substring(index, index + 1).charAt(0);
// 判断是否是符号
if (operStack.isOper(ch)) {
if (operStack.isEmpty()) {
// 当前栈为空,直接入栈
operStack.push(ch);
} else {
// 栈不为空,判断当前操作符的优先级是否小于等于栈中的操作符
if (operStack.priority(ch) <= operStack.priority((char)operStack.peek())) {
num1 = numStack.pop();
num2 = numStack.pop();
op = operStack.pop();
res = numStack.cal(num1, num2, op);
numStack.push(res);
operStack.push(ch);
} else {
// 当前操作符的优先级大于栈中的操作符
operStack.push(ch);
}
}
} else {
// 如果是数字,需要考虑多位数字
numStr += ch;
// 如果ch是最后一位,则直接入栈
if (index == inffixExpression.length() - 1) {
numStack.push(Integer.parseInt(numStr));
} else {
// 判断下一位是数字还是字符,若是数字,则直接进行下一轮循环。反之,则将当前数字存入数字栈中
if (operStack.isOper(inffixExpression.substring(index + 1, index + 2).charAt(0))) {
numStack.push(Integer.parseInt(numStr));
numStr = ""; // 下一次用来重新拼接数字,每次要清空
}
}
}
// 每次查完一个字符后,index自增
index++;
// 判断表达式是否已扫描完
if (index >= inffixExpression.length()){
break;
}
}
// 遍历完字符串后,从栈中取出数据进行运算,直到符号栈为空退出
while (true) {
if (operStack.isEmpty()) {
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
op = operStack.pop();
res = numStack.cal(num1, num2, op);
numStack.push(res);
}
// 符号栈为空时,数字栈的中的数字就是运算结果
System.out.println(inffixExpression + "=" + numStack.pop());
}
}
class InffixStack {
private int[] arr;
private int maxSize;
private int top;
public InffixStack(int maxSize) {
this.maxSize = maxSize;
this.arr = new int[maxSize];
this.top = -1;
}
public int peek() {
return arr[top];
}
public void push(int val) {
if (isFull()) {
throw new RuntimeException("栈满,入栈失败!");
}
arr[++top] = val;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空,出栈失败!");
}
return arr[top--];
}
public void print() {
if (isEmpty()) {
throw new RuntimeException("栈空,出栈失败!");
}
System.out.print("栈元素:");
for (int i = top; i >= 0 ; i--) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public boolean isEmpty() {
if (top == -1) {
return true;
}
return false;
}
public boolean isFull() {
if (top == maxSize - 1) {
return true;
}
return false;
}
public boolean isOper(char ch) {
if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
return true;
}
return false;
}
public int priority(char ch) {
if (ch == '*' || ch == '/') {
return 1;
} else if (ch == '+' || ch == '-') {
return 0;
} else {
return -1;
}
}
public int cal(int num1, int num2, int op) {
int res = 0;
switch (op) {
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num2 / num1;
break;
}
return res;
}
}