Data Structure Using C++
Stack Data Structure
Postfix Evaluation Using Linked List Stack
class stack
{
private:
node *head;
public:
stack();
void push(int val);
int pop ();
int top();
int isEmpty ();
};
stack::stack()
{
head=NULL;
}
void stack::push(int val)
{
node *ptr= new node (val);
ptr->setNext(head);
head=ptr;
}
int stack::pop()
{
if(isEmpty())
{
cout<<"Error: Stack is empty. can't pop element."<<endl;
}
else
{
int val=head->get();
head=head->getNext();
return val;
}
}
int stack::top()
{
return head->get();
}
int stack::isEmpty()
{
return head==NULL;
}
int main ()
{
stack s;
char str[15]={'6','2','3','+','-','3','8','2','/','+','*','2','^','3'
,'+'};
int i=0;
int op1, op2, result=0, ans=0;
while(str[i]!='\0')
{
char ch=str[i];
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='^')
{
op2=s.pop();
op1=s.pop();
cout<<op1<<" "<<op2<<endl;
if(ch=='+')
{
result=op1+op2;
}
else if(ch=='-')
{
result=op1-op2;
}
else if(ch=='*')
{
result=op1*op2;
}
else if(ch=='/')
{
if(op2!=0)
{
result=op1/op2;
}
}
else if(ch=='^'){
result=pow(op1,op2);
}
cout<<endl<<result<<endl;
s.push(result);
}
else
{
ch=ch-48;
s.push(ch);
}
i++;
}
ans=s.pop();
cout<<"Result is : "<<ans<<endl;
}
Let me know in the comment section if you have any question.
Previous Post:
Postfix Evaluation Using Array Stack In Data Structure Using C++
Comments
Post a Comment