Stack Push Pop Traverse Implementation and Operations in Data Structures (C plus plus)

Stack Push Pop Traverse Implementation and Operations in Data Structures (C plus plus)

In this tutorial, we will learn Stack Push Pop Traverse Implementation and Operations in Data Structures (C plus plus).

/*
Implementation of Stack through Linked List
 */
 
#include<iostream>
#include<cstdlib>

using namespace std;
 
/*
Declaring the node
 */
struct node
{
    int info;
    struct node *link;    
}*top;
 
/*
Declaring the class
 */
class stack_vals
{
    public:
        node *push(node *, int);
        node *pop(node *);
        void traverse(node *);
        stack_vals()
        {
            top = NULL;
        }               
};

int main()
{
    int val_selection, object;
    stack_vals sl;
    while (1)
    {
        cout<<"\n----------"<<endl;
        cout<<"Stack Operations:"<<endl;
        cout<<"\n----------"<<endl;
        cout<<"1. Push Element"<<endl;
        cout<<"2. Pop Element"<<endl;
        cout<<"3. Traverse"<<endl;
        cout<<"4. Quit"<<endl;
        cout<<"Please Enter your choice:";
        cin>>val_selection;
        switch(val_selection)
        {
        case 1:
            cout<<"Please enter the desired value: ";
            cin>>object;
            top = sl.push(top, object);
            break;
        case 2:
            top = sl.pop(top);
            break;
        case 3:
            sl.traverse(top);
            break;
        case 4:
            exit(1);
            break;
        default:
            cout<<"Invalid input"<<endl;
        }
    }
    return 0;
}
 
/*
 Push Element
 */
node *stack_vals::push(node *top, int object)
{
    node *temporary;
    temporary = new (struct node);
    temporary->info = object;
    temporary->link = top;
    top = temporary;
    return top;
}
 
/*
Pop Element
 */
node *stack_vals::pop(node *top)
{
    node *temporary;
    if (top == NULL)
        cout<<"Empty Stack"<<endl;
    else
    {       
        temporary = top;
        cout<<"Element Popped Successfully: "<<temporary->info<<endl;
        top = top->link;
        delete(temporary);
    }
    return top;
}
 
/*
 * Traversing
 */
void stack_vals::traverse(node *top)
{       
    node *temp1;
    temp1 = top;
    if (top == NULL)
        cout<<"Empty Stack"<<endl;
    else
    {
        cout<<"Elements in stack are following:"<<endl;
        while (temp1 != NULL)
        {
            cout<<temp1->info<<endl;
            temp1 = temp1->link;
        }
    }
}

Output:

Stack Push Pop Traverse Implementation and Operations in Data Structures (C plus plus)
Stack Push Pop Traverse Implementation and Operations in Data Structures (C plus plus)
Prof.Fazal Rehman Shamil (Available for Professional Discussions)
1. Message on Facebook page for discussions,
2. Video lectures on Youtube
3. Email is only for Advertisement/business enquiries.