Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- struct node{
- int data;
- struct node* next;
- };
- struct node* top= (struct node*)malloc(sizeof(node));
- string a,b;
- char aa;
- int i,j,k,l,x;
- void push(int n)
- {
- struct node* newnode=(struct node*)malloc(sizeof(node));
- newnode->data=n;
- newnode->next=top;
- top=newnode;
- }
- char peek()
- {
- return top->data;
- }
- bool isEmpty()
- {
- if(top->next==NULL)
- return 1;
- else
- return 0;
- }
- void pop()
- {
- if(isEmpty()==0)
- top=top->next;
- }
- /*void traversal(struct node* dummy)
- {
- while(dummy->next!=NULL)
- {
- cout <<dummy->data <<" ";
- dummy=dummy->next;
- }
- cout <<endl;
- }*/
- int precidence(char c)
- {
- if(c=='*')
- return 2;
- else if(c=='/')
- return 2;
- else if(c=='+')
- return 1;
- else if(c=='-')
- return 1;
- }
- int main()
- {
- top->next=NULL;
- cout<<"Infix Expression: ";
- cin >>a;
- for(i=0; i<a.size(); i++)
- {
- if(a[i]>='0' && a[i]<='9')
- b += a[i];
- else
- {
- while(precidence(a[i])<precidence(peek()))
- {
- b += peek();
- pop();
- }
- push(a[i]);
- }
- }
- while(isEmpty() == 0)
- {
- b += peek();
- pop();
- }
- cout <<"Postfix Expression: "<< b <<endl;
- for(i=0; i<b.size(); i++)
- {
- if(b[i] >= '0' && b[i] <= '9')
- push(b[i]);
- else
- {
- int p = peek()-'0';
- pop();
- int q = peek()-'0';
- pop();
- if(b[i]=='*')
- x = q*p;
- else if(b[i]=='/')
- x = q/p;
- else if(b[i]=='+')
- x = q+p;
- else if(b[i]=='-')
- x = q-p;
- aa = x+'0';
- push(aa);
- }
- }
- cout<<"Result: "<< x <<endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment