Java 实例 - 利用堆栈将中缀表达式转换成后缀表达式

以下实例演示了如何使用堆栈进行表达式的堆栈将中缀(Infix)表达式转换成后缀(postfix)表达式:

InToPost.java 文件

  1. import java.io.IOException;
  2. public class InToPost {
  3. private Stack theStack;
  4. private String input;
  5. private String output = "";
  6. public InToPost(String in) {
  7. input = in;
  8. int stackSize = input.length();
  9. theStack = new Stack(stackSize);
  10. }
  11. public String doTrans() {
  12. for (int j = 0; j < input.length(); j++) {
  13. char ch = input.charAt(j);
  14. switch (ch) {
  15. case '+':
  16. case '-':
  17. gotOper(ch, 1);
  18. break;
  19. case '*':
  20. case '/':
  21. gotOper(ch, 2);
  22. break;
  23. case '(':
  24. theStack.push(ch);
  25. break;
  26. case ')':
  27. gotParen(ch);
  28. break;
  29. default:
  30. output = output + ch;
  31. break;
  32. }
  33. }
  34. while (!theStack.isEmpty()) {
  35. output = output + theStack.pop();
  36. }
  37. System.out.println(output);
  38. return output;
  39. }
  40. public void gotOper(char opThis, int prec1) {
  41. while (!theStack.isEmpty()) {
  42. char opTop = theStack.pop();
  43. if (opTop == '(') {
  44. theStack.push(opTop);
  45. break;
  46. }
  47. else {
  48. int prec2;
  49. if (opTop == '+' || opTop == '-')
  50. prec2 = 1;
  51. else
  52. prec2 = 2;
  53. if (prec2 < prec1) {
  54. theStack.push(opTop);
  55. break;
  56. }
  57. else
  58. output = output + opTop;
  59. }
  60. }
  61. theStack.push(opThis);
  62. }
  63. public void gotParen(char ch){
  64. while (!theStack.isEmpty()) {
  65. char chx = theStack.pop();
  66. if (chx == '(')
  67. break;
  68. else
  69. output = output + chx;
  70. }
  71. }
  72. public static void main(String[] args)
  73. throws IOException {
  74. String input = "1+2*4/5-7+3/6";
  75. String output;
  76. InToPost theTrans = new InToPost(input);
  77. output = theTrans.doTrans();
  78. System.out.println("Postfix is " + output + '\n');
  79. }
  80. class Stack {
  81. private int maxSize;
  82. private char[] stackArray;
  83. private int top;
  84. public Stack(int max) {
  85. maxSize = max;
  86. stackArray = new char[maxSize];
  87. top = -1;
  88. }
  89. public void push(char j) {
  90. stackArray[++top] = j;
  91. }
  92. public char pop() {
  93. return stackArray[top--];
  94. }
  95. public char peek() {
  96. return stackArray[top];
  97. }
  98. public boolean isEmpty() {
  99. return (top == -1);
  100. }
  101. }
  102. }

以上代码运行输出结果为:

  1. 124*5/+7-36/+
  2. Postfix is 124*5/+7-36/+