fork download
  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3. import java.util.Stack;
  4.  
  5. public class Main {
  6.  
  7. public static void main(String[] args) {
  8. // TODO Auto-generated method stub
  9.  
  10. /** input 是測試資料**/
  11. String input = "(((a+b)*c)/(d-e))";
  12. InfixToPrefix(input);
  13. }
  14.  
  15. public static void InfixToPrefix(String input) {
  16. // 只能用3個Q
  17. Queue<Character> Q1 = new LinkedList<Character>();
  18. // stack(用兩個Q來模擬,故Q的數量已經用完)
  19. Stack<Character> s = new Stack<>();
  20. // 整個掃過一次
  21. for (int index = 0; index < input.length(); index++) {
  22. // ch是用來重複檢驗的輸入
  23. char ch = input.charAt(index);
  24. // 輸入是'('或者是變數, 推入stack s中
  25. if (ch != ')' && !isOperator(ch))
  26. s.push(ch);
  27. else {
  28. // 若是 operator
  29. if (isOperator(ch)) {
  30. // 把到'('以前的內容都拉出來 , 存到Q1內
  31. while (!s.isEmpty() && s.peek() != '(')
  32. Q1.add(s.pop());
  33. // 再放回去
  34. while (!Q1.isEmpty())
  35. s.push(Q1.poll());
  36. // 再拿出來
  37. while (!s.isEmpty() && s.peek() != '(')
  38. Q1.add(s.pop());
  39. // 如此以後這群Q1內的東西再放回去s時順序才不會反序
  40.  
  41. // 把'('清除
  42. s.pop();
  43. // 把該operator加入stack內
  44. s.push(ch);
  45. // 把剛剛拿出來的全丟進去
  46. while (!Q1.isEmpty())
  47. s.push(Q1.poll());
  48. }
  49. }
  50. }
  51. // 貼出內容
  52. while (!s.isEmpty())
  53. Q1.add(s.pop());
  54. while (!Q1.isEmpty())
  55. s.push(Q1.poll());
  56. while (!s.isEmpty())
  57. System.out.print(s.pop());
  58. }
  59.  
  60. public static boolean isOperator(Character c) {
  61. if (c == '+' || c == '-' || c == '*' || c == '/')
  62. return true;
  63. return false;
  64. }
  65.  
  66. }
  67.  
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
/*+abc-de