2013-03-14 78 views
0

我需要實現綴到後綴轉換算法來計算表達式a + b *的CD/E需要創建綴以後綴算法

我還需要做到這一點使用隊列(我相信2個不同的隊列堆棧是需要)

我使用DoubleLinkList創建了隊列類,現在只需要創建這個問題的算法。儘管如此,但我對於如何解決這個問題卻很失落。任何幫助,將不勝感激!

至今(我知道這是非常錯誤的),我有:

string infix = "a+b*c-d/e"; 
    Queue *holder = new Queue(); 
    Queue *newstring = new Queue(); 
    int length = infix.length(); 
    char temp; 
    char prev; 
    for(int i=0; i<length; i++) 
    { 
     temp = infix[i]; 
     if((temp == '+') || (temp == '-') || (temp == '*') || (temp == '/')) 
     { 
      if (holder->isEmpty()) 
      { 
       holder->queue(temp); 
      } 
      if(temp<holder.enqueue()) 
      { 

      } 
     } 
     holder->queue(temp); 

    } 
+0

快速谷歌搜索 「轉換到綴後綴」 產生[本內容豐富的文章(http://scriptasylum.com/tutorials/infix_postfix /algorithms/infix-postfix/index.htm)。你可能想從那裏開始。 – 2013-03-14 17:32:33

回答

2

我想這是一個家庭作業,讓你找出你自己的編程細節是非常重要的。該算法的大綱如下:

Define a stack 
Go through each character in the string 
If it is between 0 to 9, append it to output string. 
If it is left brace push to stack 
If it is operator *+-/ then 
      If the stack is empty push it to the stack 
      If the stack is not empty then start a loop: 
          If the top of the stack has higher precedence 
          Then pop and append to output string 
          Else break 
        Push to the stack 

If it is right brace then 
      While stack not empty and top not equal to left brace 
      Pop from stack and append to output string 
      Finally pop out the left brace. 

If there is any input in the stack pop and append to the output string. 
+0

對不起,碰到一箇舊帖子,但我已經搜索了同樣的東西,我想知道爲什麼這總是使用這種特定的堆棧算法,以及它背後的原理。我可以看到它的工作原理,但對於爲什麼我有點困惑,我使用了一種替代算法來獲得相同的結果。你可以添加的任何細節都會很棒。 – ffledgling 2013-12-30 21:02:03