Site icon T4Tutorials.com

Program to evaluate an expression using stacks in Data Structures (C plus plus)

Program to evaluate an expression using stacks in Data Structures (C plus plus)

In this tutorial, we will learn about the Program to evaluate an expression using stacks in Data Structures (C plus plus). 

/*C++ Program to Evaluate an  Expression using Stacks*/

#include <iostream>
#include <string.h>

using namespace std;

struct node
{
    int info;
    node *next;
}
*p = NULL, *top = NULL, *save = NULL, *ptr;

void insert(int x)
{
    p = new node;
    p->info = x;
    p->next = NULL;
    if (top == NULL)
    {
        top = p;
    }
    
    else
    {
        save = top; 
        top = p;
        p->next = save;
    }
}

char del()
{
    if (top == NULL)
    {
        cout<<"Underflowed ";
    }
    
    else
    {
        ptr = top;
        top = top->next;
        return(ptr->info);
        delete ptr;
    }
}

int main()
{
    char z[30];
    int x, y;
    
	cout<<"Please enter the balanced expression"<<endl;
    cin>>z;
    
    for (int u = 0; u < strlen(z); u++)
    {
        if (z[u] >= 48 && z[u]  <= 57)
            insert(z[u]-'0');
        else if (z[u] >= 42 && z[u] <= 47)
        {
            x=del();
            y=del();
            switch(z[u])
            {
            case '+':
                    insert(x+y);
                break;
            case '-':
                insert(x-y);
                break;
            case '*':
                insert(x*y);
            break;
            case '/':      
                insert(x/y);
                break;
            }
        }
    }
    cout<<"The answer is "<<del()<<endl;
    
}

Output

Program to evaluate an expression using stacks in Data Structures (C plus plus)
Exit mobile version