Advertisement
Mubtasim_Arnab

Infix to Postfix

Feb 21st, 2018
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #define MAX_SIZE 20
  4.  
  5. int stack[MAX_SIZE];
  6. int top = -1;
  7.  
  8. int isEmpty() {
  9. return top == -1;
  10. }
  11.  
  12. void push(int item) {
  13. if(top == MAX_SIZE-1) {
  14. printf("Error: Stack Overflow\n");
  15. return;
  16. }
  17. stack[++top] = item;
  18. }
  19.  
  20. char pop() {
  21. if(isEmpty()) {
  22. printf("Error: Stack is Empty\n");
  23. return '$';
  24. }
  25. return stack[top--];
  26. }
  27.  
  28. int precedence(char symbol) {
  29. if(symbol == '(') {
  30. return 0;
  31. } else if(symbol == '+' || symbol == '-') {
  32. return 1;
  33. } else if(symbol == '*' || symbol == '/') {
  34. return 2;
  35. } else if(symbol == '^') {
  36. return 3;
  37. }
  38. }
  39.  
  40. int main() {
  41.  
  42. char infix[20], x, temp;
  43. int i = 0;
  44. printf("Enter Infix Expression :\n");
  45. scanf("%s", infix);
  46. printf("Expression in Postfix Notation :\n");
  47. while(infix[i] != '\0') {
  48. x = infix[i];
  49. if(x == '(') {
  50. push(x);
  51. } else if(isalnum(x)) {
  52. printf("%c", x);
  53. } else if(x == ')') {
  54. while((temp = pop()) != '(') {
  55. printf("%c", temp);
  56. }
  57. } else {
  58. if(!isEmpty()) {
  59. while(precedence(stack[top]) >= precedence(x)) {
  60. printf("%c", pop());
  61. }
  62. }
  63. push(x);
  64. }
  65. i++;
  66. }
  67. while(!isEmpty()) {
  68. printf("%c", pop());
  69. }
  70. printf("\n");
  71.  
  72. return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement