al__nasim

infix to postfix(normal)

Jul 13th, 2016
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct node{
  5. int data;
  6. struct node* next;
  7. };
  8. struct node* top= (struct node*)malloc(sizeof(node));
  9. string a,b;
  10. char aa;
  11. int i,j,k,l,x;
  12.  
  13. void push(int n)
  14. {
  15. struct node* newnode=(struct node*)malloc(sizeof(node));
  16. newnode->data=n;
  17. newnode->next=top;
  18. top=newnode;
  19. }
  20. char peek()
  21. {
  22. return top->data;
  23. }
  24. bool isEmpty()
  25. {
  26. if(top->next==NULL)
  27. return 1;
  28. else
  29. return 0;
  30. }
  31. void pop()
  32. {
  33. if(isEmpty()==0)
  34. top=top->next;
  35. }
  36. /*void traversal(struct node* dummy)
  37. {
  38. while(dummy->next!=NULL)
  39. {
  40. cout <<dummy->data <<" ";
  41. dummy=dummy->next;
  42. }
  43. cout <<endl;
  44. }*/
  45. int precidence(char c)
  46. {
  47. if(c=='*')
  48. return 2;
  49. else if(c=='/')
  50. return 2;
  51. else if(c=='+')
  52. return 1;
  53. else if(c=='-')
  54. return 1;
  55. }
  56. int main()
  57. {
  58. top->next=NULL;
  59.  
  60. cout<<"Infix Expression: ";
  61. cin >>a;
  62. for(i=0; i<a.size(); i++)
  63. {
  64. if(a[i]>='0' && a[i]<='9')
  65. b += a[i];
  66. else
  67. {
  68. while(precidence(a[i])<precidence(peek()))
  69. {
  70. b += peek();
  71. pop();
  72. }
  73. push(a[i]);
  74. }
  75. }
  76. while(isEmpty() == 0)
  77. {
  78. b += peek();
  79. pop();
  80. }
  81. cout <<"Postfix Expression: "<< b <<endl;
  82. for(i=0; i<b.size(); i++)
  83. {
  84. if(b[i] >= '0' && b[i] <= '9')
  85. push(b[i]);
  86. else
  87. {
  88. int p = peek()-'0';
  89. pop();
  90. int q = peek()-'0';
  91. pop();
  92.  
  93. if(b[i]=='*')
  94. x = q*p;
  95. else if(b[i]=='/')
  96. x = q/p;
  97. else if(b[i]=='+')
  98. x = q+p;
  99. else if(b[i]=='-')
  100. x = q-p;
  101. aa = x+'0';
  102. push(aa);
  103. }
  104. }
  105. cout<<"Result: "<< x <<endl;
  106. return 0;
  107. }
Advertisement
Add Comment
Please, Sign In to add comment