Advertisement
Aniket_Goku

infix -> prefix

Aug 27th, 2020
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. //infix -> prefix
  2. #include<stdio.h>
  3. #include<conio.h>
  4. #include<string.h>
  5. char stack[50],infix[50],prefix[50];
  6. int top=-1;
  7. char pop()
  8. {
  9. char ch;
  10. ch=stack[top];
  11. top--;
  12. return ch;
  13. }
  14. void push(char ch)
  15. {
  16. top++;
  17. stack[top]=ch;
  18. }
  19. int main()
  20. {
  21. int i,j=0;
  22. clrscr();
  23.  
  24. printf("\nEnter the Infix expression: ");
  25. gets(infix);
  26. strcat(infix,")"); //insert ENd ")"
  27. strrev(infix); //revers string
  28. strcat(infix,"("); //insert starting"("
  29. puts(strrev(infix));
  30. strrev(infix);
  31. for(i=0;i<=strlen(infix);i++)
  32. {
  33. switch(infix[i])
  34. {
  35. case ')':
  36. push(')');
  37. break;
  38.  
  39. case '(':
  40.  
  41. while(stack[top]!=')')
  42. {
  43. prefix[j]=pop();
  44. j++;
  45.  
  46. }
  47. top--;
  48. break;
  49.  
  50. case '^':
  51. push('^');
  52. break;
  53.  
  54. case '*':
  55. case '/':
  56. while(stack[top]=='^')
  57. {
  58. prefix[j]=pop();
  59. j++;
  60. }
  61. push(infix[i]);
  62. break;
  63.  
  64. case '+':
  65. case '-':
  66. while(stack[top]=='^'||stack[top]=='*' ||stack[top]=='/')
  67. {
  68. prefix[j]=pop();
  69. j++;
  70. }
  71. push(infix[i]);
  72. break;
  73.  
  74. default:
  75. prefix[j]=infix[i];
  76. j++;
  77. }
  78. printf("\n[%d]-> %c || %s || %s \n",i+1,infix[i],stack,prefix);
  79.  
  80. }
  81. while(top!=-1)
  82. {
  83. prefix[j]=pop();
  84. j++;
  85. }
  86. stack[0]=NULL;
  87. printf("\n[%d]-> %c || %s || %s \n",i+1,infix[i],stack,strrev(prefix));
  88. prefix[j]=NULL;
  89. printf("\n %s <=== INFIX TO PREFIX ===> %s",strrev(infix),prefix);
  90. getch();
  91. return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement