written 7.9 years ago by
yashbeer
★ 11k
|
|
Program:
#include<iostream>
#include<conio.h>
using namespace std;
struct node
{
int info;
struct node *next;
};
class StackUsingLinkedList
{
struct node *top;
public:
StackUsingLinkedList()
{
top=NULL;
}
void push();
void pop();
void display();
};
//To push an element to stack
void StackUsingLinkedList::push()
{
int value;
struct node *ptr;
cout<<"PUSH OPERATION"<<endl;
cout<<"Enter the element to insert: ";
cin>>value;
ptr=new node;
ptr->info=value;
ptr->next=NULL;
if(top!=NULL)
ptr->next=top;
top=ptr;
cout<<"New element "<< value <<" is inserted to the stack";
}
//To pop an element from stack
void StackUsingLinkedList::pop()
{
struct node *temp;
if(top==NULL)
{
cout<<"Stack is empty"<<endl;
return;
}
temp=top;
top=top->next;
cout<<"POP OPERATION"<<endl;
cout<<"The element popped is: "<<temp->info<<endl;
delete temp;
}
//To display the elements of stack
void StackUsingLinkedList::display()
{
struct node *ptr1=top;
if(ptr1 == NULL)
{
cout<<"Stack is Empty"<<endl;
}
else
{
cout<<"Following are the elements of stack"<<endl;
while(ptr1!=NULL)
{
cout<<ptr1->info<<" ->";
ptr1=ptr1->next;
}
cout<<"NULL";
}
}
int main()
{
StackUsingLinkedList stack;
int choice;
cout<<"STACK USING LINKED LIST"<<endl;
while(1)
{
cout <<"\n1.Push 2.Pop 3. Display Stack 4.Exit\nEnter ur choice"<<endl;
cin>>choice;
switch(choice)
{
case 1:
stack.push();
break;
case 2:
stack.pop();
break;
case 3:
stack.display();
break;
case 4:
return 0;
break;
default:
cout<<"Incorrect choice!!";
break;
}
}
return 0;
}
Sample output:
STACK USING LINKED LIST
1.Push 2.Pop 3. Display Stack 4.Exit
Enter ur choice
1
PUSH OPERATION
Enter the element to insert: 11
New element 11 is inserted to the stack
1.Push 2.Pop 3. Display Stack 4.Exit
Enter ur choice
1
PUSH OPERATION
Enter the element to insert: 12
New element 12 is inserted to the stack
1.Push 2.Pop 3. Display Stack 4.Exit
Enter ur choice
1
PUSH OPERATION
Enter the element to insert: 13
New element 13 is inserted to the stack
1.Push 2.Pop 3. Display Stack 4.Exit
Enter ur choice
3
Following are the elements of stack
13 ->12 ->11 ->NULL
1.Push 2.Pop 3. Display Stack 4.Exit
Enter ur choice
2
POP OPERATION
The element popped is: 13
1.Push 2.Pop 3. Display Stack 4.Exit
Enter ur choice
3
Following are the elements of stack
12 ->11 ->NULL