Advertisement
thinhckhcmus

Trung Tố Sang Hậu Tố ( BQT CODER )

Sep 18th, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. using namespace std;
  4. #define MAX 1000
  5. struct stack {
  6. int top;
  7. char data[MAX];
  8. };
  9. void init(stack& s) {
  10. s.top = 0;
  11. }
  12. int isEmpty(stack s) {
  13. return (s.top == 0);
  14. }
  15. int isFull(stack s) {
  16. return (s.top == MAX);
  17. }
  18. void push(stack& s, char x) {
  19. if (!isFull(s)) {
  20. s.data[s.top] = x;
  21. s.top++;
  22. }
  23. }
  24. char top(stack s) {
  25. return s.data[s.top - 1];
  26. }
  27. char pop(stack& s) {
  28. if (!isEmpty(s)) {
  29. s.top--;
  30. return s.data[s.top];
  31. }
  32. }
  33. struct queue {
  34. int front, rear;
  35. char data[MAX];
  36. int n;
  37. };
  38. void initQueue(queue& q) {
  39. q.front = 0;
  40. q.rear = -1;
  41. q.n = 0;
  42. }
  43. bool isFullQueue(queue q) {
  44. return (q.n == MAX);
  45. }
  46. bool enQueue(queue& q, char x) {
  47. if (isFullQueue(q)) {
  48. return false;
  49. }
  50. q.rear = (q.rear + 1) % MAX;
  51. q.data[q.rear] = x;
  52. q.n++;
  53. return true;
  54. }
  55. bool isNumber(char c) {
  56. return c >= '0' && c <= '9';
  57. }
  58. bool isBest(char x, char y) {
  59. if (x == '(') {
  60. return false;
  61. }
  62. if (x == '*' || x == '/') {
  63. return true;
  64. }
  65. if (x == '+' || x == '-') {
  66. if (y == '*' || y == '/') {
  67. return false;
  68. }
  69. return true;
  70. }
  71. }
  72. int Precedence(char x)
  73. {
  74. if (x == '(')
  75. return 0;
  76. if (x == '+' || x == '-')
  77. return 1;
  78. if (x == '*' || x == '/' || x == '%')
  79. return 2;
  80.  
  81. return 3;
  82. }
  83. void infixToPostfix(char p[], queue& q) {
  84. char x;
  85. stack s;
  86. init(s);
  87. for (int i = 0; i < strlen(p); i++) {
  88. if (p[i] == '(') {
  89. push(s, p[i]);
  90. }
  91. else if (isNumber(p[i])) {
  92. enQueue(q, p[i]);
  93. }
  94. else if (p[i] == ')') {
  95. do {
  96. x = pop(s);
  97. if (x != '(') {
  98. enQueue(q, x);
  99. }
  100. } while (x != '(');
  101. }
  102. else {
  103. x = top(s);
  104. while (isBest(x,p[i])) {
  105. x = pop(s);
  106. enQueue(q, x);
  107. x = top(s);
  108. }
  109. push(s, p[i]);
  110. }
  111. }
  112. while (!isEmpty(s)) {
  113. x = pop(s);
  114. enQueue(q, x);
  115. }
  116. }
  117. void Output(queue q) {
  118. for (int i = q.front; i <= q.rear; i++) {
  119. cout << q.data[i];
  120. }
  121. }
  122. void main() {
  123. queue q;
  124. initQueue(q);
  125. char p[] = "3+4";
  126. infixToPostfix(p, q);
  127. Output(q);
  128. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement