3.2 Stack Using Linked List
3.2 Stack Using Linked List
Stack Representation
A stack can be represented using linked list
which is the dynamic representation stack.
Operations on Stack using Linked list
Display
Push Operation
Push
1. create a new node ( say temp) containing
the information to be inserted.
2. node temp;
3. temp->info=data;
4. temp->next=NULL;
Push
5. If the stack is empty i.e. top = NULL then
make the new node as the first node in the
list.
Push
5. If the stack is empty i.e. top = NULL then
make the new node as the first node in the
list
6. top=temp; top
Push
7. If the stack is not empty then
- Store the address of head node in the next
part of the new node
temp->next=top
Push
2. top=top->next
Display
Display
void display( )
{
slist * curn;
if(top==NULL) // CASE-1
printf(“STACK IS EMPTY");
else // CASE-2
{
curn=top;
while(curn !=NULL)
{
Printf(“\t%d”,curn->info );
curn =curn->next ;
}
}
}
Display
CASE-1
1. if(top==NULL)
printf(“Stack is empty”);
Display
CASE-2
1. else
2. { curn=top;
3. while(curn !=NULL)
4. {
5. Printf(“\t%d”,curn->info );
6. curn =curn->next ;
7. }
8. }
9. }
Curn is 100 its not equal to NULL, so curn->info that’s 10 is displayed and
curn moves to next node
10
Display
CASE-2
1. else
2. { curn=top;
3. while(curn !=NULL)
4. {
5. Printf(“\t%d”,curn->info );
6. curn =curn->next ;
7. }
8. }
9. }
Curn is 200 its not equal to NULL, so curn->info that’s 20 is displayed and
curn moves to next node
10 20
Display
CASE-2
1. else
2. { curn=top;
3. while(curn !=NULL)
4. {
5. Printf(“\t%d”,curn->info );
6. curn =curn->next ;
7. }
8. }
9. }
Curn is 300 its not equal to NULL, so curn->info that’s 30 is displayed and
curn moves to next node
10 20 30
Display
CASE-2
1. else
2. { curn=top;
3. while(curn !=NULL)
4. {
5. Printf(“\t%d”,curn->info );
6. curn =curn->next ;
7. }
8. }
9. }
Now curn is NULL so while is terminated.
10 20 30