Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include"stack.h"
- using namespace std;
- class Expression{
- Stack s;
- public:
- int evaluate(char* str){
- char* temp = str;
- Stack s;
- while(*temp !='\0'){
- if(*temp>='0' && *temp<='9'){
- s.push(*temp-48);
- }
- else{
- int val1 = s.pop();
- int val2 = s.pop();
- switch (*temp)
- {
- case '+': s.push( val2 + val1); break;
- case '-': s.push(val2 - val1); break;
- case '*': s.push(val2 * val1); break;
- case '/': s.push(val2/val1); break;
- }
- }
- temp++;
- }
- return s.pop();
- }
- int precedence(char symbol){
- if(symbol=='+' || symbol == '-')
- return 1;
- else if(symbol=='*' || symbol == '/')
- return 2;
- else if(symbol=='^')
- return 3;
- }
- int isOperator(char ch){
- if(ch=='+' || ch=='-' || ch=='*' ||ch=='/'||ch=='^')
- return true;
- return false;
- }
- void conversion(char* str){
- char *temp = str;
- char ch;
- while(*temp!='\0'){
- if(*temp == '('){
- s.push(*temp);
- }
- else if(*temp>='0' && *temp<='9')
- cout<<*temp;
- else if(isOperator(*temp)){
- //cout<<"*temp: and "<<*temp<<" "<<s.counter()<<endl;
- if(s.isEmpty())
- s.push(*temp);
- else if(s.StackTop()=='('){ //cout<<*temp<< "Pushed";
- s.push(*temp);
- }
- else if(precedence(*temp) > precedence(s.StackTop())){
- s.push(*temp);
- }
- else{
- char ch = s.pop();
- cout<<ch;
- do{
- ch = s.StackTop();
- if(isOperator(ch) && (precedence(*temp)> precedence(ch)))
- break;
- ch=s.pop();
- if(isOperator(ch))
- cout<<ch;
- }while((ch != '(') && !s.isEmpty());
- s.push(*temp);
- }
- }
- else if(*temp ==')'){
- do{
- ch = s.pop();//cout<<ch<<" EElements "<<s.counter()<<endl;
- if(ch!='(')
- cout<<ch;
- }while(!s.isEmpty());
- }
- temp++;
- }
- if(!s.isEmpty()){
- do{
- //cout<<"While "<<s.counter()<<endl;
- ch=s.pop();
- if(ch!='(')
- cout<<ch;//" elements "<<s.counter()<<endl;
- }while(!s.isEmpty());
- }
- }
- };
- int main(){
- cout<<"Welcome to linked implementation of Stack";
- Expression pe;
- char str[100];
- int choice=1;
- do{
- cout<<"Enter the Expression: "; //1+2*3
- cin>>str; //123*+
- pe.conversion(str);
- cout<<"Choice "<<endl;
- cin>>choice;
- }while(choice==1);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment