Stack (Code) :

<br />#include<iostream>
#include<conio.h>
using namespace std;
struct stack
{
int data;
struct stack *link;
}*head=NULL,*nptr,*tmp,*ptr;

void push()
{
int d;
cout<<"Enter a data:\n";
cin>>d;
nptr=new stack;
if(nptr==NULL)
{
cout<<"Out of Memory...! Overflow...!!\n";
}
else
{
nptr->data=d;
nptr->link=head;
head=nptr;
cout<<"node has been inserted at top successfully !!\n";
}
}

void pop()
{
int info;
if(head==NULL)
{
cout<<"Underflow...!!\n";
}
else
{
tmp=head;
info=tmp->data;
head=head->link;
tmp->link=NULL;
delete tmp;
cout<<info<<" deleted from top..!!\n";
}
}

void display()
{
if(head==NULL)
{
cout<<"Stack is empty....!!!\n";
}
else
{
ptr=head;
cout<<"Head->";
while(ptr!=NULL)
{
cout<<"["<<ptr->data<<"] ->";
ptr=ptr->link;
}
cout<<"NULL";
}
}
int main()
{
int opn,elem;
do
{
cout<<"\n### Linked List Implementation of STACK Operations ###\n\n";
cout<<"\n Press 1-Push, 2-Pop, 3-Display,4-Exit\n";
cout<<"Your option ? ";
cin>>opn;
switch(opn)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3: cout<<"Linked List Implementation of Stack: Status:\n";
display(); break;
case 4: cout<<"\n Terminating \n\n"; break;
default: cout<<"\nInvalid Option !!! Try Again !! \n\n";
break;
}
cout<<"\n\n Press a Key to Continue . . . \n";
getch();
}while(opn != 4);

getch();
return 0;
}

corollary :
stack

Leave a comment