今天是栈和堆列 妈呀太难了
import java.util.Stack;
public class day7 {
//中缀转后缀
public static void m2l(String p){//p = ((a+b*h)*(c-d))/(e+f)
Stack<Character> stack = new Stack<Character>();
String s = "";
for(int i=0;i<p.length();i++){
char c = p.charAt(i);
if(c=='('){
stack.push(c);
}else if(c==')'){
char c0 = stack.pop();
while(c0!='(') {//要出栈得值
s += c0;
c0 = stack.pop();
}
}else if(c=='*'||c=='/'){
if(!stack.isEmpty()){
char c1 = stack.peek();
while(c1!='+'&&c1!='-'&&c1!='('){
s+=stack.pop();
if(stack.isEmpty()){
break;
}else{
c1 = stack.peek();
}
}
}
stack.push(c);
}else if(c=='+'||c=='-'){
if(!stack.isEmpty()) {
char c2 = stack.peek();
while (c2 != '(') {
s += stack.pop();
if(stack.isEmpty()){
break;
}else{
c2 = stack.peek();
}
}
}
stack.push(c);
}else{
s+=c;
}
}
while (!stack.isEmpty()){
s+=stack.pop();
}
System.out.println(s);
}
public static void main(String[] args){
String p = "a+b-c";
//abh*+cd-*ef+/
m2l(p);
/*MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.push(4);
myStack.push(5);
myStack.foreach();
System.out.println(myStack.pop());
System.out.println(myStack.peek());
myStack.foreach();*/
/* int a = 1;
int b = 2;
int c = a+b;*/
//中缀表达式,前缀运算符 (+ab),后缀运算符(ab+)
//((a+b)*(c-d))/(e+f)
// 后:ab+cd-*ef+/
}
}
环形栈的出栈和入栈,这里用到了之前学过的三木运算符,简单易懂方便查看。
还是得把数组与数据结构好好敲一敲。
明天周四啦,后天去接你(手动比心,biubiubiu);