基于《数据结构Java语言描述》笔记(3.0)使用一个表达式求值,
栈:
作为一种特殊的线性表,可以采用顺序存储结构和链式存储结构。采用顺序存储结构的栈称为顺序栈(Sequential Stack)。
栈顶:
用变量top表示栈顶元素在数组中的位置,也把top称为栈顶指针
栈空:
栈中有一个元素时,top值为0,因此一般用top=-1,表示栈空
栈满:
设数组的长度为length,当top=length-1时,表示栈满
栈底:
数组下标为0的一端表示栈底
SeqStank类
public class SeqStank extends Object {
private Object[] stack = null;
private int length;//顺序栈的容量
private int top;//栈顶指针
public SeqStank() {//栈初始化
stack = new Object[8];
length = 8;
top = -1;//栈初始化,没有元素
}
public SeqStank(int size) {
stack = new Object[size];
length = size;
top = -1;
}
//元素入栈
public void push(Object a) {//栈已满,则输出,未满入栈
if (top == length - 1) {
System.out.println("已满");
} else {
stack[++top] = a;//栈顶先加1,再将元素放入栈顶位置
}
}
public boolean isEnty() {
return top == -1;
}
public Object pop() {
if (this.isEnty()) {
System.out.println("栈为空");
return -1;
} else{
return stack[top--];
}
}
public Object peek(){
if(this.isEnty()){
System.out.println("栈空");
return -1;
}
else {
return stack[top];
}
}
public boolean operator(char a){
switch (a){
case '+':
case '-':
case '*':
case '/':
return true;
default:
return false;
}
}
public int caculate(int num1,int num2,char b){
switch (b){
case '+':
return num1+num2;
case '-':
return num1-num2;
case '*':
return num2*num1;
case '/':
return num1/num2;
default:
return -1;
}
}
public int priority(char a) {
if (a == '+' || a == '-') {
return -1;
}else {
return -2;
}
}
}
Test类
public class Test {
public static void main(String[] args) {
String expression = "2-5/3+5-1"; //请输入你的表达式
SeqStank num = new SeqStank();
SeqStank oper = new SeqStank();
Object num1 = 0;
Object num2 = 0;
Object res;
char a=0;
for (int i = 0; i < expression.length(); i++) {
char symbol = expression.charAt(i);//读取字符
switch (symbol) {
case '+':
case '-':
case '*':
case '/':
//判断符号前栈的情况
if (!oper.isEnty()) {
if (oper.priority(symbol) <= oper.priority((char) oper.peek())){}
num1=num.pop();//若是运算符,栈顶两个元素连续出栈
num2=num.pop();
a = (char) oper.pop();
res = num.caculate(Integer.parseInt(num2.toString()),Integer.parseInt(num1.toString()),a);
num.push(res);
oper.push(symbol);
} else {
oper.push(symbol);
}
break;
default:
num.push(symbol);
break;
}
}
while (true) {
if (oper.isEnty()) {
break;
}
num1 = num.pop();
num2 = num.pop();
a = (char) oper.pop();
res = num.caculate(Integer.parseInt(num2.toString()), Integer.parseInt(num1.toString()), a);
num.push(res);
}
Object res2 = num.pop();
System.out.println(res2);
}
}
结果: