Saturday, 1 February 2014

Check whether the given linked list is either NULL-terminated or ends in cycle(cyclic)

Linked List is Cyclic means in linked list any two nodes will be pointing to the same node .We cannot fimd the last node of Cyclic Linked List.

Null terminated Linked Lsit means its last node will be pointing to the NULL.
(a.k.a. Simple Typical Linked List)


NULL Terminated Linked List
Cyclic  Linked List

Logic: We can detect loop in list when we find two notes pointing the 
same node (two node's next address is one node's address).If we find node 
pointing to NULL ,it is NULL terminated List.


Logic1:Brute Force Approach : We point one node and scan entire list if any another node points to that node.It will take O(n^2). But if list contain cycle we can't get end of the list. So, this method won’t work because of Infinite Loop.



Logic 2:Floyd Cycle:

In this algo, We are maintaing two pointers named slow and fast pointer. 
slow pointer moves one node at time while fast node moves two nodes at time
So,IF there is loop, Both pointers will meet at some instant, this can be said 
as there is loop in list. IF anywhere pointer finds node having pointing to NULL, IT can be easily said to be NULL Terminated list.



Order Complexity : O(n)

Space Complexity:  O(1)







No comments:

Post a Comment