Advertisement
Guest User

segfault infix to postfix

a guest
Nov 29th, 2013
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. /* convert infix notation to postfix notation */
  2. #include<stdio.h>
  3. #include<string.h>
  4. char stackPop(char *, int *); //stack array and address of top.
  5. void stackPush(char *, char, int *); //stack array, element to push, address of top.
  6. void main()
  7. {
  8.     int i, top = -1;
  9.     char stack[100],infix[100],postfix[100],p;
  10.     printf("Enter the infix expression: ");
  11.     scanf("%s",infix);
  12.     stackPush(stack,'(',&top);
  13.     strcat(")",infix);
  14.     i=0;
  15.     while (top!=-1) //process stops when stack is empty.
  16.     {
  17.         if(infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/')
  18.         {
  19.             if (infix[i] == '+' || infix[i] == '-')
  20.             {
  21.                 while(stack[top] == '+' || stack[top] == '-' || stack[top] == '*' || stack[top] == '/')
  22.                 {
  23.                     p = stackPop(stack, &top);
  24.                     postfix [strlen(postfix)] = p;
  25.                 }
  26.             }
  27.             else
  28.             {
  29.                 while(stack[top] == '*' || stack[top] == '/')
  30.                 {
  31.                     p = stackPop(stack, &top);
  32.                     postfix [strlen(postfix)] = p;
  33.                 }
  34.             }
  35.             stackPush(stack,infix[i],&top);
  36.         }
  37.         else if(infix[i] == '(')
  38.             stackPush(stack,infix[i],&top);
  39.         else if(infix[i] == ')')
  40.         {
  41.             p = stackPop(stack,&top);
  42.             while (p!= '(')
  43.             {
  44.                 postfix [strlen(postfix)] = p;
  45.                 p = stackPop(stack,&top);
  46.             }
  47.         }
  48.         else //for infix[i] == operand
  49.             postfix [strlen(postfix)] = infix[i];
  50.         i++;
  51.     }
  52.     printf("The postfix notation is %s", postfix);
  53. }
  54.  
  55. void stackPush(char *stack, char item, int *top)
  56. {
  57.     stack[++(*top)]=item;
  58. }
  59.  
  60. char stackPop(char *stack, int *top)
  61. {
  62.     int item = stack[(*top)--];
  63.     return item;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement