public class stack {
public static void main(String[] args) {
String expression="1+2";
//创建两个栈,一个存放数据,一个存放符号串
ArrayStack numstack=new ArrayStack(20);
ArrayStack operstack=new ArrayStack(20);
int index=0;
int num1=0;
int num2=0;
int oper=0;
int res=0;
char ch=' ';
while (true) {
ch = expression.substring(index, index + 1).charAt(0);
if (operstack.isOper(ch)) {
//运算符
if (!operstack.isnull()) {
if (operstack.pro(ch) <= operstack.pro(operstack.peek())) {
num1 = numstack.pop();
num2 = numstack.pop();
oper = operstack.pop();
res = operstack.cal(num1, num2, oper);
numstack.push(res);
operstack.push(ch);
} else {
operstack.push(ch);
}
} else {
operstack.push(ch);
}
}else {
numstack.push(ch-48);
}
index++;
if (index >= expression.length()){
break;
}
}
while (true){
if (operstack.isnull()){
break;
}
num1 = numstack.pop();
num2 = numstack.pop();
oper = operstack.pop();
res = operstack.cal(num1, num2, oper);
numstack.push(res);
}
double res2=numstack.pop();
System.out.println("表达式:"+exxpression+"="res2);
}
}
class ArrayStack{
private int maxSize;
private int[] stack;
private int top=-1;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack =new int[this.maxSize];
}
public int peek(){
return stack[top];//返回栈顶的值
}
public boolean isnull(){
return top==-1;
}
//判断栈是否满
public boolean isfull(){
return top==maxSize-1;
}
//入栈
public void push(int value){
//判断是否为栈满
if(isfull()){
System.out.println("栈满");
return;
}
top++;
stack[top]=value;
}
//出栈
public int pop(){
//判断是否为空
if (isnull()){
System.out.println("栈空,无法出栈");
return 0;
}
int value=stack[top];//定义变量存储出栈的元素
top--;
return value;
}
//显示栈的情况:遍历栈,从栈顶开始显示数据
public void list(){
if(isnull()){
System.out.println("栈空,无数据");
return;
}
//需要从栈顶开始显示数据
for (int i=top;i>=0;i--){
System.out.println("栈中数据为:"+stack[i]);
}
}
public int pro(int oper){
if (oper=='*'||oper=='/') {
return 1;
}else 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;
}
}
结果为:
表达式:1+2=3