Friday, 15 December 2017

Write a C++ program to implement the Stack ADT using singly linked list.

A stack is an ordered collection of data items into which new items may be inserted and from which data items may be deleted at one end. Stack are also called Last-In-First-out (LIFO) lists.

Implementation of the above problem:
#include<iostream>
using namespace std;
template<class t>
class node
{
public:
t info;
node *link;
};
template <class t>
class StackADT
{
virtual void Push()=0;
virtual void Pop()=0;
virtual void Top()=0;
virtual void Display()=0;
};
template<class t>
class StackLinkImp : public StackADT<t>
{
public:
t item;
node<t> *temp, *top;
StackLinkImp()
{
top=NULL;
}
void Push()
{
temp=new node<t>;
cout<<"Enter the itemto be insrted on to the stack:";
cin>>item;
if(top==NULL)
temp->link=NULL;
else
temp->link=top;
temp->info=item;
top=temp;
cout<<"Insertion Completed Successfully";
}
void Pop()
{
if(top==NULL)
cout<<"Stack is empty";
else
{
item=top->info;
top=top->link;
cout<<"The deleted element is:"<<item;
}
}
void Top()
{
if(top==NULL)
cout<<"Stack is empty";
else
cout<<"The top element is:"<<top->info;
}
void Display()
{
if(top==NULL)
cout<<"Stack is empty";
else
{
temp=top;
cout<<"The elements in the stack are:";
while(temp!=NULL)
{
cout<<temp->info<<" ";
temp=temp->link;
}
}
}
};
int main()
{
int ch;
StackLinkImp<int> s1;
do
{
cout<<"\n****Menu****";
cout<<"\n1. Push\n2. Pop\n3. Top\n4. Display\n5. Exit";
cout<<"\nEnter ur choice:";
cin>>ch;
switch(ch)
{
case 1: s1.Push();
break;
case 2: s1.Pop();
break;
case 3: s1.Top();
break;
case 4: s1.Display();
break;
case 5: exit(1);
default: cout<<”Entered Wrong Choice”;
}
}
while(1);
return 0;
}


Thanks
Mukesh Rajput

No comments:

Post a Comment

Thanks
Mukesh Rajput