fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define MAX_SIZE 100
  6.  
  7. // Define a stack structure
  8. struct Stack {
  9. int top;
  10. char items[MAX_SIZE];
  11. };
  12.  
  13. // Function to initialize an empty stack
  14. void initialize(struct Stack *s) {
  15. s->top = -1;
  16. }
  17.  
  18. // Function to check if the stack is empty
  19. int isEmpty(struct Stack *s) {
  20. return s->top == -1;
  21. }
  22.  
  23. // Function to push an element onto the stack
  24. void push(struct Stack *s, char item) {
  25. if (s->top == MAX_SIZE - 1) {
  26. printf("Stack Overflow\n");
  27. exit(1);
  28. }
  29. s->items[++(s->top)] = item;
  30. }
  31.  
  32. // Function to pop an element from the stack
  33. char pop(struct Stack *s) {
  34. if (isEmpty(s)) {
  35. printf("Stack Underflow\n");
  36. exit(1);
  37. }
  38. return s->items[(s->top)--];
  39. }
  40.  
  41. // Function to check precedence of operators
  42. int precedence(char operator) {
  43. if (operator == '+' || operator == '-') {
  44. return 1;
  45. } else if (operator == '*' || operator == '/') {
  46. return 2;
  47. }
  48. return 0;
  49. }
  50.  
  51. // Function to convert infix expression to postfix notation
  52. void infixToPostfix(char infix[], char postfix[]) {
  53. struct Stack stack;
  54. initialize(&stack);
  55.  
  56. int i, j;
  57. i = j = 0;
  58.  
  59. while (infix[i] != '\0') {
  60. char token = infix[i];
  61.  
  62. if (token >= 'a' && token <= 'z') {
  63. postfix[j++] = token;
  64. } else if (token == '(') {
  65. push(&stack, token);
  66. } else if (token == ')') {
  67. while (!isEmpty(&stack) && stack.items[stack.top] != '(') {
  68. postfix[j++] = pop(&stack);
  69. }
  70. if (!isEmpty(&stack) && stack.items[stack.top] == '(') {
  71. pop(&stack); // Pop the '('
  72. }
  73. } else {
  74. while (!isEmpty(&stack) && precedence(token) <= precedence(stack.items[stack.top])) {
  75. postfix[j++] = pop(&stack);
  76. }
  77. push(&stack, token);
  78. }
  79.  
  80. i++;
  81. }
  82.  
  83. while (!isEmpty(&stack)) {
  84. postfix[j++] = pop(&stack);
  85. }
  86.  
  87. postfix[j] = '\0';
  88. }
  89.  
  90. int main() {
  91. char infix[MAX_SIZE] = "x+y"; // Predefined infix expression
  92. char postfix[MAX_SIZE];
  93.  
  94. infixToPostfix(infix, postfix);
  95.  
  96. printf("Infix: %s\n", infix);
  97. printf("Postfix: %s\n", postfix);
  98.  
  99. return 0;
  100. }
  101.  
Success #stdin #stdout 0s 5476KB
stdin
Standard input is empty
stdout
Infix: x+y
Postfix: xy+