我想编写一个程序来将输入(中缀表达式)读入Queue<char>
对象。输出应该是后缀表达式。在从队列到堆栈中获取值时我很困惑。
这是我的逻辑:
Stack<char> opStack;
Queue<char> postQ, infixQ;
// infixQ contains the infix expression to be converted.
// postQ contains the converted postfix expression.
char t;
while (infixQ is not empty) {
t = infixQ.Front();
infix.DeQueue();
if (t is a number token) // (1)
postQ.EnQueue(t);
else if (opStack.IsEmpty()) // (2)
opStack.Push(t);
else if (t is a left paren token) // (3)
opStack.Push(t);
else if (t is a right paren token) { // (4)
while (opStack.Top() is not a left paren) {
postQ.EnQueue(opStack.Top());
opStack.Pop();
}
opStack.Pop(); // discard a left paren from stack
}
else { // (5)
while ( opStack is not empty and opStack.Top() != ’(’ and precedence of t <= precedence of opStack.Top()) {
postQ.EnQueue(opStack.Top());
opStack.Pop();
}
opStack.Push(t);
}
}
// Now there are no tokens left in infixQ, so transfer remaining operators.
while (!opStack.IsEmpty()) { // (6)
postQ.EnQueue(opStack.Top());
opStack.Pop();
}