Program to implement stack using linked list
PROGRAM
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
class stacklist
{
node *start,*last,*head;
public:
void push();
void pop();
void display();
stacklist()
{
start=last=NULL;
}
};
void stacklist::push()
{
head=new node;
cout<<"Enter the data:";
cin>>head->data;
if(start==NULL)
{
head->next=NULL;
start=last=head;
}
else
{
head->next=start;
start=head;
}
}
void stacklist::pop()
{
if(start==NULL)
cout<<"List is empty\n";
else
{
node *temp=start;
cout<<"Deleted item is
"<<start->data;
if(start==last)
start=last=NULL;
else
start=start->next;
delete temp;
}
}
void stacklist::display()
{
node *temp;
temp=start;
if(temp==NULL)
cout<<"Stack is empty\n";
else
{
cout<<"Stack elements are:\n";
while(temp!=NULL)
{
cout<<temp->data<<"\t";;
temp=temp->next;
}
}
}
int main()
{
stacklist s;
int ch;
char c;
do
{
cout<<"\nMenu operations:\n”;
cout<<”1.push\n”;
cout<<”2.pop\n”;
cout<<”3.display\n”;
cout<<”Enter your choice:";
cin>>ch;
switch(ch)
{
case 1:s.push();
break;
case 2:s.pop();
break;
case 3:s.display();
break;
default:cout<<"Invalid
option\n";
}
cout<<"\nDo you want to
continue,(y/n):";
cin>>c;
}while(c=='Y'||c=='y');
return 0;
}
OUTPUT
Menu operations:
1.push
2.pop
3.display
Enter your choice:1
Enter the data:5
Do you want to
continue,(y/n):y
Menu operations:
1.push
2.pop
3.display
Enter your choice:1
Enter the data:8
Do you want to
continue,(y/n):y
Menu operations:
1.push
2.pop
3.display
Enter your choice:1
Enter the data:6
Do you want to
continue,(y/n):y
Menu operations:
1.push
2.pop
3.display
Enter your choice:3
Stack elements are:
6 8 5
Do you want to
continue,(y/n):y
Menu operations:
1.push
2.pop
3.display
Enter your choice:2
Deleted item is 6
Do you want to
continue,(y/n):y
Menu operations:
1.push
2.pop
3.display
Enter your choice:2
Deleted item is 8
Do you want to
continue,(y/n):y
Menu operations:
1.push
2.pop
3.display
Enter your choice:2
Deleted item is 5
Do you want to
continue,(y/n):y
Menu operations:
1.push
2.pop
3.display
Enter your choice:3
Stack is empty
Do you want to continue,(y/n):n
0 comments:
Post a Comment