Lab06 Stack using Linked List
Lab06 Stack using Linked List
06
Objectives:
Introduction
We go for a linked list implementation of a stack rather than an array implementation because
of the run time memory allocation feature of linked lists. In this implementation we make a
head pointer and make it point to the first created node in the stack. Whenever a new node is
pushed into the stack we make the head pointer point to the new node and the new node to
point to the already existing node that was pointed by the head pointer.
Pushing an element:
Lab Tasks:
1. Compile and examine the program provided below. Print the output in the space
provided.
Code:
#include<iostream>
using namespace std;
// POP Operation
void stack::pop()
{
struct node *temp;
if(top==NULL)
{
cout<<"\nThe stack is empty!!!";
}
temp=top;
top=top->next;
cout<<"\nPOP Operation........\nPoped value is "<<temp->data;
delete temp;
}
// Show stack
void stack::show()
{
struct node *ptr1=top;
cout<<"\nThe stack is\n";
while(ptr1!=NULL)
{
cout<<ptr1->data<<" ->";
ptr1=ptr1->next;
}
cout<<"NULL\n";
}
// Main function
int main()
{
stack s;
int choice;
while(1)
{
cout<<"\n-----------------------------------------------------------";
cout<<"\n\t\tSTACK USING LINKED LIST\n\n";
cout<<"1:PUSH\n2:POP\n3:DISPLAY STACK\n4:EXIT";
cout<<"\nEnter your choice(1-4): ";
cin>>choice;
switch(choice)
{
case 1:
s.push();
break;
case 2:
s.pop();
break;
case 3:
s.show();
break;
case 4:
return 0;
break;
default:
cout<<"\nPlease enter correct choice(1-4)!!";
break;
}
}
return 0;
}
Output:
2. Develop a program that displays the top item of the stack.
3. Develop a program that implements Stack using Doubly Linked List
Code:
Output: