首先看思路
思路就是这么个思路
需要注意的点我都写在代码里面了
栈和双向链表都是自己封装
适合数据结构与算法初级选手
上代码
public class CalculatorOfStack {
private String calculator;//需要处理的表达式
private ListStack nums;//数字栈
private ListStack opers;//操作栈
CalculatorOfStack(String calculator){
this.calculator = calculator;
nums = new ListStack();
opers = new ListStack();
System.out.println(toAnswer());
}
//处理函数
public int toAnswer(){
int index = 0;
while(true)
{
if(index>=calculator.length())
break;
char ch = calculator.charAt(index);
if(ch == ' ')//空格直接跳过iu
{
index++;
continue;
}
if(Character.isDigit(ch))
{
int num = ch-'0';
if(index<calculator.length()-1&&Character.isDigit(calculator.charAt(index+1)))
{
//获取多位数
while(index<calculator.length()-1&&Character.isDigit(calculator.charAt(index+1)))
{
char t = calculator.charAt(index+1);
num *= 10;
num += t-'0';
index++;
}
}
index++;
nums.push(num);
continue;
}
else if(isOper(ch))
{
//处理操作符
if(opers.isEmpty())
{
//为空则直接加入
opers.push(ch);
}
else
{
int oper = opers.pop();
if(priority((char)oper)>=priority(ch))
{
//比较优先级,若当前操作符大于等于栈顶操作符,则运算
int num1 = nums.pop();
int num2 = nums.pop();
int res = operation(num1,num2,(char)oper);
nums.push(res);
if(!opers.isEmpty())//这一步很重要,如果opers不为空则须继续判断,ch后面再添加,必须先continue,index不动
continue;
opers.push(ch);
}
else
{
//若当前操作符<栈顶操作符,则继续
opers.push(oper);
opers.push(ch);
}
}
index++;
}
}
while(!opers.isEmpty())
{
int num1 = nums.pop();
int num2 = nums.pop();
int ch = opers.pop();
int res = operation(num1,num2,(char)ch);
nums.push(res);
}
return nums.pop();
}
//判断是否是操作符
public boolean isOper(int oper){
return oper=='+'||oper=='-'||oper=='*'||oper=='/';
}
//操作符赋优先级
public int priority(int oper){
if(oper == '*'||oper == '/')
return 1;
else if(oper == '+'||oper == '-')
return 0;
else
return -1;
}
//运算函数
public int operation(int num1,int num2,char oper){
int res = 0;
switch (oper)
{
case '+':
return num1+num2;
case '-':
return num2-num1;
case '*':
return num1*num2;
case '/':
return num2/num1;
default:
break;
}
return -1;
}
}
class ListStack{
private dlist head;//头节点
private dlist top;//栈顶节点
ListStack(){
head = new dlist();
top = head;
}
//判断栈是否为空
public boolean isEmpty(){
return head.next == null;
}
//入栈
public void push(int val){
dlist t = new dlist(val);
top.next = t;
t.pre = top;
top = top.next;
}
//出栈
public int pop(){
if(!isEmpty())
{
int val = top.val;
top = top.pre;
top.next = null;
return val;
}
return -1;
}
public void print(){
dlist l = head.next;
while(l != null)
{
System.out.println(l.val);
l = l. next;
}
}
}
//双向链表
class dlist{
int val;
dlist next;//指向下一个
dlist pre;//指向上一个
dlist(){
next = null;
}
dlist(int val,dlist next,dlist pre){
this.next = next;
this.val = val;
this.pre = pre;
}
dlist(int val){
this.val = val;
}
}