11. Linked List Implementation
Why?
• When the size is unknown
• No limitations for the number of nodes
Why should we refer the beginning
of the linked
list as the top of the stack?
• Time complexity
stac
k
top
12. Stack Implementation by using Linked Lists
How to write a program for stack using linked list
implementation?
1) push() - similar to the code of inserting the node at the beginning of
the singly linked list
2) pop() - similar to the code of deleting the first node at the beginning
of the singly linked list
3) stackoverflow() - use malloc() function. If stack overflow occurs
returns null.
4) stackunderflow() - occurs when top equals to null.
13. Steps for Implementation
1) Structure of the node and how to create the
top variable pointer
struct node{
Int data;
struct node*link;
}
*top=NULL;
14. 1) Create a new node
struct node*newNode;
newNode = malloc(size
of(newNode));
newNode->data=data;
newNode->link=NULL;
Push Function
15. Push Function (Cont.)
2) Put the address of the first node of the linked
list to the link part of the new node
newNode->link=top;
3) Update the top pointer and make it point to the
new node of the linked list
top=newNode;
16. Pop Function
1) Create a temporary pointer for the purpose of deletion
struct node*temp;
2) Update the temporary pointer. So that it can be point to
the first node of the linked list
Temp = top;
3)Store the value of the first node (pop returns)
int val=temp->data;
17. Pop Function (Cont.)
4) Update the top pointer. So that it can be point to the
next node of the linked list
top = top->link;
5) Delete the node pointed by the temporary pointer.
free(temp);
temp=NULL;
6)Return the value of the first node
return val;
18. Peek Function
1) int peek(){
if(isEmpty()){
printf(“stackoverflow”)
exit(1);
}
Return top->data;
};
If the input array is sorted in a strictly increasing order, the last element
is always a peek element. Looks at the object at the top of this stack
without removing it from the stack.