栈Stack:是继承vector的数据结构
Object pop(); 出栈
void push(Object); 压栈
boolean empty(); 判断栈为空
Object peek(); 获取栈顶元素 该元素不出栈
int search (Object); 获取元素位置
使用栈完成计算表达式的结果
如3+2*6-2
使用两个栈 一个数据栈numstack 一个符号栈operstack
1.使用一个index值为索引 遍历表达式
2.遍历到数据,如数据栈
3.遍历到符号
3.1如符号表为空 符号入栈
3.2如当前操作符优先级小于等于栈顶优先级 pop数据栈两个数进行栈顶符号的运算 再将检测到的符号如栈
3.3如当前操作符优先级大于栈顶优先级 符号入栈
4.扫描结束了 顺序取出两栈元素 进行运算 符号栈为空是数据栈中的唯一数为运算结果
package fsdf;
import java.util.*;
public class g1{
public static void main (String []args) {
int index =0,temp=0;
String Str = new String("3+5*4-2*2+5*2/2");
Stack <Integer> numStack = new Stack<Integer>();
Stack <Character> operStack = new Stack<Character>();
while(index < Str.length() ) {
if(Str.charAt(index)<'9'&&Str.charAt(index)>='0') {
// int i=(int)Str.charAt(index)-48;
// System.out.println("num"+i);
numStack.push((int)Str.charAt(index)-48);
}else {
if(operStack.empty() == true) {
operStack.push(Str.charAt(index));
}else if(Str.charAt(index)=='+'||Str.charAt(index)=='-'&&(operStack.peek()=='*'||operStack.peek()=='/' )) {
switch (operStack.pop()) {
case '+': numStack.push((int)(numStack.pop()+(int)numStack.pop())); break;
case '-': numStack.push((int)(numStack.pop()*(-1)+(int)numStack.pop())); break;
case '*': numStack.push((int)(numStack.pop()*(int)numStack.pop())); break;
case '/': numStack.push((int)(1.0/numStack.pop()*(int)numStack.pop())); break;
}
operStack.push(Str.charAt(index));
}else{
operStack.push(Str.charAt(index));
}
}
index ++;
}
/* while(operStack.empty() == false) {
System.out.println(operStack.pop());
}
while(numStack.empty() == false) {
System.out.println(numStack.pop());
}*/
while(numStack.empty() == false) {
if(operStack.empty() == false && numStack.empty() == false) {
if(operStack.peek() == '+') {
operStack.pop();
temp += numStack.pop();
}else if(operStack.peek() == '-') {
operStack.pop();
temp -= numStack.pop();
}else if(operStack.peek() == '*') {
operStack.pop();
numStack.push((int)(numStack.pop()*(int)numStack.pop()));
}else if(operStack.peek() == '/') {
operStack.pop();
numStack.push((int)(1.0/numStack.pop()*(int)numStack.pop()));
}else {}
}
else{
temp += numStack.pop();
}
}
System.out.println(temp);
}
}