Circular Single Linked List
Circular Single Linked List
UNIT-2
Header
Other operations
5. Destroy
6. IsEmpty
7. reverse a linked list
8. Copying
9. Merging (combine two linked lists)
Insertion on Circular linked list
• There are various positions where can be
node inserted.
Header ptr
Header ptr
2
Make header to point to the new node.
Header
Header ptr
Header ptr
1
Insertion is completed
Algorithm to insert a new node at the End of Circular Linked List
ptr
Header
Move ptr to point to last node of list
Header ptr
Header ptr
The NEXT part of PTR is made to point to the second node of the list
ptr
Header
1
Destroy first node
ptr
Header
Header
Deletion is completed
Algorithm to delete a node at the front of Circular Linked List
Step 1: IF Header = NULL
Print “List is empty”
Go to Step 8
[END OF IF]
Step 2: SET PTR =
Step 3: Header
Step 4: Repeat Step 4 while PTR NEXT != Header
SET PTR = PTR NEXT
Step 5: [END OF LOOP]
Step 6: SET PTR NEXT = Header NEXT
Step 7: Free Header
Step 8: SET Header = PTR NEXT
EXIT
Time Complexity : O(n)
Deleting the Last Node from a Circular Linked List
• Suppose we want to delete data value 5 from the list.
Header Given Circular Linked List
Make two temporary pointers ptr and preptrto point to the first
node of the List
ptr
Header
Preptr
Preptr Move PTR to point to the last node of the list and PREPTR
always points to the node preceding PTR.
Header ptr
Preptr ptr
Header
Destroy the node pointed by ptr
Header ptr
Deletion is completed
Algorithm to delete a node at the last of Circular Linked List
Step 1: IF Header = NULL
Print “List is empty”
Go to Step 8
[END OF IF]
Step 2: SET PTR =
Header
Step 3: SET Preptr =
Step 4: Header
Step 5: Repeat Step
4 and 5 while PTR
NEXT != Header
Step 6: SET
Step 7: Preptr =
Step 8: EXIT PTR Time Complexity : O(n)
SET PTR = PTR NEXT
Traversing a Circular Linked List
• Traversing a linked list means accessing the nodes of the
list in order to perform some processing on them.
• Example: Displaying the contents of Linked list, Counting
number of nodes in the linked list, etc..
Algorithm for Displaying Circular Linked List:
Step -1: ptr = header
Step-2: Repeat Steps-3 and 4 while ptr
Step-3:
Next!= print ptr data
Step-4: Set ptr = ptr next
Header [END OF LOOP]
Step- 5: print ptr data #prints last
Step 5: Stop node
Time Complexity: O(n)
Displaying Circular Linked list
header
Given Linked List
Start Traversing
header ptr
header ptr