2013-04-06 106 views
0

你好,我正在練習Java上的一些堆棧,我試圖做一個有關堆棧的問題。我試圖編寫一個採用後綴表示法並將其轉換爲中綴的方法。這是我到目前爲止有:從後綴堆棧轉換到中綴

` 
public void convertion() { 
     Stack<Integer> stack;   // For evaluating the expression. 
     stack = new Stack<Integer>(); // Make a new, empty stack. 

     Scanner scan = new Scanner(postfix); 

     int t1, t2 = 0;  //Operands 

     boolean check = false; 


     while (scan.hasNext() && !check) { 
      if (scan.hasNextInt()) { 
       int operand = scan.nextInt(); 
       stack.push(operand); 
      } else { 
       char operator = scan.next().charAt(0); 
       try { 

         while(stack.) 


       } catch (EmptyStackException e) { 
        answer = "Malformed postfix expression"; 
        check = true; 
       } 

      } 
     } 
     scan.close(); 
     try { 
      answer = "" + stack.pop(); 
     } catch (EmptyStackException e) { 
      answer = "Malformed postfix expression"; 
     } 
    } 
` 

遇到問題的部分IM是什麼,我應該提上嘗試的一部分。基本上,我把所有我找到的數字都推入堆棧,但是一旦我找到一個操作符,我該如何合併兩個操作數和操作符。

謝謝。

+1

這是一個很好的案例爲第一工作了使用的紙張和鉛筆的算法。嘗試一些後綴表達式。跟蹤堆棧的狀態,並查看它與您想要的輸出之間的關係。我不明白你爲什麼只把Integer放在你的堆棧上。 – 2013-04-06 01:08:31

回答

-1

你想彈出頂部的兩個棧元素,對他們進行適當的操作,然後推回結果:

try { 
    int o1 = stack.pop().intValue(); 
    int o2 = stack.pop().intValue(); 
    switch (operator) { 
     case '+': stack.push(new Integer(o1 + o2)); 
        break; 
     case '-': stack.push(new Integer(o1 - o2)); 
        break; 
     ... 
    } 
} 
catch (EmptyStackException e) { 
    ... 
+0

他沒有評估。他正在將後綴轉換爲中綴。 – EJP 2017-02-27 00:31:55