This C++ program, using a stack data strucure, computes value of postfix expression which pushes operands and pops these values on encountering an operator.
Here is the source code of the C++ program to display the value of the postfix expression given as input. This C++ program is successfully compiled and run on DevCpp, a C++ compiler. The program output is given below.
/*
* C++ Program to Evaluate an Expression using Stacks
*/
#include <iostream>
#include <conio.h>
#include <string.h>
using namespace std;
struct node
{
int data;
node *next;
}*p = NULL, *top = NULL, *save = NULL, *ptr;
void push(int x)
{
p = new node;
p->data = x;
p->next = NULL;
if (top == NULL)
{
top = p;
}
else
{
save = top;
top = p;
p->next = save;
}
}
char pop()
{
if (top == NULL)
{
cout<<"underflow!!";
}
else
{
ptr = top;
top = top->next;
return(ptr->data);
delete ptr;
}
}
int main()
{
char x[30];
int a, b;
cout<<"enter the balanced expression\n";
cin>>x;
for (int i = 0; i < strlen(x); i++)
{
if (x[i] >= 48 && x[i] <= 57)
push(x[i]-'0');
else if (x[i] >= 42 && x[i] <= 47)
{
a=pop();
b=pop();
switch(x[i])
{
case '+':
push(a+b);
break;
case '-':
push(a-b);
break;
case '*':
push(a*b);
break;
case '/':
push(a/b);
break;
}
}
}
cout<<"ans is "<<pop()<<endl;
getch();
}
Output enter the balanced expression 567+8-/ ans is -1
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Next Steps:
- Get Free Certificate of Merit in Data Structure I
- Participate in Data Structure I Certification Contest
- Become a Top Ranker in Data Structure I
- Take Data Structure I Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Programming Books
- Buy Data Structure Books
- Apply for Computer Science Internship
- Buy Computer Science Books
- Practice Design & Analysis of Algorithms MCQ