Advertisement
Unique144

Infix to Prefix

Nov 12th, 2021
909
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 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.     char rev[100];
  41.     gets(rev);
  42.     strcpy(exp,strrev(rev));
  43.     for(int i=0; i<strlen(exp); i++) {
  44.         if(exp[i]=='(')
  45.         exp[i]=')';
  46.         else if(exp[i]==')')
  47.         exp[i]='(';
  48.         else
  49.         continue;
  50.     }
  51.     for(int i=0; i< strlen(exp); i++) {
  52.         if(exp[i]=='(')
  53.         push(&top, '(');
  54.         else if (exp[i]>=65 && exp[i]<=90) {
  55.             out[x++] = exp[i];
  56.         }
  57.         else if(exp[i]==')') {
  58.             while(peak(&top)!='(') {
  59.                 out[x++] = pop(&top);  
  60.             }
  61.             char temp = pop(&top);
  62.         }
  63.         else {
  64.             if(exp[i]=='+'||exp[i]=='-') {
  65.                 if(peak(&top)=='*'||peak(&top)=='/'||peak(&top)=='^') {
  66.                     out[x++] = pop(&top);
  67.                     push(&top, exp[i]);
  68.                 }
  69.                 else {
  70.                     push(&top, exp[i]);
  71.                 }
  72.             }
  73.             else if(exp[i]=='/'||exp[i]=='*') {
  74.                 if(peak(&top)=='^') {
  75.                     out[x++] = pop(&top);
  76.                     push(&top, exp[i]);
  77.                 }
  78.                 else {
  79.                     push(&top, exp[i]);
  80.                 }
  81.             }
  82.             else {
  83.                 push(&top, exp[i]);
  84.             }
  85.         }
  86.         }
  87.         strcpy(out, strrev(out));
  88.         printf("Output: %s", out);
  89.        
  90.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement