数组栈
public class ArrayStack {
int maxsize;
int stack[];
int top;
ArrayStack(int maxsize) {
this.maxsize = maxsize;
top = -1;
stack = new int[maxsize];
}
boolean isEmpty() {
return top == -1;
}
boolean isFull() {
return top == maxsize - 1;
}
void push(int item) {
if (!isFull()) {
top++;
stack[top] = item;
}
}
int pop() {
if (!isEmpty()) {
int i = stack[top];
top--;
return i;
}
return -1;
}
boolean isOpera(char opera) {
return opera == '+' || opera == '-' || opera == '*' || opera == '/';
}
int getPriority(char opera) {
int priority = -1;
if (opera == '+' || opera == '-') {
priority = 0;
} else if (opera == '*' || opera == '/') {
priority = 1;
}
return priority;
}
int cul(int num1, int num2, char ope) {
int res = 0;
switch (ope) {
case '+':res = num1+num2;
break;
case '-':res = num2 - num1;
break;
case '*': res = num2 * num1;
break;
case '/':res=num2 / num1;
break;
default:break;
}
return res;
}
char getTop(){
return (char) stack[top];
}
}
计算方法
public void operateString(String operation){
int[] index = new int[2];
ArrayStack numStack = new ArrayStack(operation.length());
ArrayStack operaStack = new ArrayStack(operation.length());
String num ="";
int res = 0;
for (int i = 0;i < operation.length() ;i++)
{
if (operaStack.isOpera(operation.charAt(i)))
{
index[1] = i;
if (index[0] == 0)
{
for (int j = index[0];j < index[1];j++)
{
num = num+operation.charAt(j);
}
}
else {
for (int j = index[0]+1;j < index[1];j++)
{
num = num+operation.charAt(j);
}
}
index[0] = index[1];
numStack.push(Integer.parseInt(num));
num="";
if (operaStack.isEmpty()||operaStack.getPriority(operaStack.getTop()) < operaStack.getPriority(operation.charAt(i)))
{
operaStack.push(operation.charAt(i));
}
else {
if (operaStack.getPriority(operaStack.getTop()) >= operaStack.getPriority(operation.charAt(i)))
{
int num1 = numStack.pop();
int num2 = numStack.pop();
char ope = (char) operaStack.pop();
int cul = numStack.cul(num1, num2, ope);
numStack.push(cul);
operaStack.push(operation.charAt(i));
}
}
}
}
for (int i = index[1]+1;i < operation.length();i++)
{
num = num+operation.charAt(i);
}
numStack.push(Integer.parseInt(num));
while (!operaStack.isEmpty())
{
int num1 = numStack.pop();
int num2 = numStack.pop();
char ope = (char) operaStack.pop();
res = numStack.cul(num1, num2, ope);
numStack.push(res);
}
System.out.println(numStack.pop());
}
存在问题
1.当开头的运算符为‘-’时,会计算错误。解决方法也很简单,特殊情况特殊对待:当发现第一个运算符为-时,直接将num1取反相加。