2013-08-01 19 views
3

我想编写一个程序来将输入(中缀表达式)读入到Queue<char>对象中。输出应该是后缀表达式。从队列中取值的时候我很困惑。从In fi x到Postfix的转换

这是我的逻辑:

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(); 
} 

谁能帮助我吗?

+10

究竟哪里存在您需要帮助的问题? “调车场”算法非常简单,甚至可以在维基百科上找到它。你可以在这里找到帮助,但你需要确定你的问题。 –

回答

0

我不明白你的问题在哪里。如果有帮助,我可以建议你在this的文章。它很好地解释了代码本身。