Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define mx 30
- int i(0);
- class node
- {
- public:
- int info;
- node *link;
- };
- node *head = NULL, *tmp = NULL;
- void push(int val)
- {
- node *ptr = new node();
- ptr->info = val;
- ptr->link = head;
- head = ptr;
- i++;
- }
- int top()
- {
- return head->info;
- }
- int pop()
- {
- int val = head->info;
- head = head->link;
- return val;
- }
- bool isEmpty()
- {
- if(head == NULL)
- {
- cout<<"\nStack Underflow!!!!\n\n";
- return true;
- }
- return false;
- }
- bool isFull()
- {
- if(i >= mx)
- {
- cout<<"\nStack Overflow!!!\n\n";
- return true;
- }
- return false;
- }
- bool isOperator(char ch)
- {
- if(ch == '+' || ch == '-' || ch == '*' || ch == '/')
- return true;
- return false;
- }
- bool isNumeric(char ch)
- {
- if(ch >= '0' && ch <= '9')
- return true;
- return false;
- }
- int perform(int a, int b, char ch)
- {
- if(ch == '+')
- return a+b;
- if(ch == '-')
- return a-b;
- if(ch == '*')
- return a*b;
- if(ch == '/')
- return a/b;
- }
- int evaluatePrefix(string exp)
- {
- int i, j, k, sz, op1, op2;
- sz = exp.size() - 1;
- for(i = sz; i >= 0; i--)
- {
- if(exp[i] == ' ' || exp[i] == ',')
- continue;
- else if(isOperator(exp[i]))
- {
- op1 = pop();
- op2 = pop();
- k = perform(op1, op2, exp[i]);
- push(k);
- }
- else if(isNumeric(exp[i]))
- {
- int a, b, c, d, oprnd;
- oprnd = 0;
- d = 1;
- for(; i >= 0 && isNumeric(exp[i]); i--, d *= 10)
- oprnd = (exp[i] - '0') * d + oprnd;
- i++;
- push(oprnd);
- }
- else
- {
- cout<<"The expression contains wrong symbol.\n";
- exit(0);
- }
- }
- return k;
- }
- int main()
- {
- int i, j, k, n;
- string str;
- getline(cin, str);
- cout<<evaluatePrefix(str)<<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement