Advertisement
Unique144

Infix to Postfix

Nov 12th, 2021
836
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.47 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. struct node {
  5.     char data;
  6.     struct node * next;
  7. };
  8.  
  9. void push (struct node **top, char c) {
  10.     struct node *temp = (struct node*)malloc(sizeof(struct node));
  11.     temp -> next = NULL;
  12.     temp->data = c;
  13.     temp -> next = *top;
  14.     *top = temp;
  15. }
  16.  
  17. int pop (struct node **top) {
  18.     struct node *p = *top;
  19.     if(p!=NULL) {
  20.         int popped = p->data;
  21.         *top = p->next;
  22.         return popped;
  23.     }
  24.     else {
  25.         printf("Empty Stack");
  26.         return -999;
  27.     }  
  28. }
  29.  
  30. int peak(struct node **top) {
  31.     return ((*top)->data);
  32. }
  33.  
  34. int main() {
  35.     struct node * top = NULL;
  36.     int x=0;
  37.     printf("Enter the FPE Infix expression: ");
  38.     char exp[100];
  39.     char out[100];
  40.     gets(exp);
  41.     for(int i=0; i< strlen(exp); i++) {
  42.         if(exp[i]=='(')
  43.         push(&top, '(');
  44.         else if ((exp[i]>=65 && exp[i]<=90)||(exp[i]>=48 && exp[i]<=57)) {
  45.             out[x++] = exp[i];
  46.         }
  47.         else if(exp[i]==')') {
  48.             while(peak(&top)!='(') {
  49.                 out[x++] = pop(&top);  
  50.             }
  51.             char temp = pop(&top);
  52.         }
  53.         else {
  54.             if(exp[i]=='+'||exp[i]=='-') {
  55.                 if(peak(&top)=='*'||peak(&top)=='/'||peak(&top)=='^') {
  56.                     out[x++] = pop(&top);
  57.                     push(&top, exp[i]);
  58.                 }
  59.                 else {
  60.                     push(&top, exp[i]);
  61.                 }
  62.             }
  63.             else if(exp[i]=='/'||exp[i]=='*') {
  64.                 if(peak(&top)=='^') {
  65.                     out[x++] = pop(&top);
  66.                     push(&top, exp[i]);
  67.                 }
  68.                 else {
  69.                     push(&top, exp[i]);
  70.                 }
  71.             }
  72.             else {
  73.                 push(&top, exp[i]);
  74.             }
  75.         }
  76.         }
  77.        
  78.         printf("Output: %s", out);
  79.        
  80.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement