Monday, 3 February 2014

Check whether the given linked list is either NULL-terminated or ends in cycle(cyclic).If there is a cycle find the start node of the list.

To find length of Cycle, we will use Floyd algorithm. We will use http://pakaprogramming.blogspot.in/2014/02/check-whether-given-linked-list-is.html  and extend it.
The total number of red dotted node=length of cycle 


Now follow these steps.

Now we need to compute starting node of loop. So, above logic will perfactly works.
When slow and fast pointer will meet (detect as loop ) at some point in list,
now follow this instructions.

When slowptr==fastptr

- make slowptr=head
-now move slowptr and fastptr one node at time  ( previously fastptr was moving two nodes
at time .Now move it one node at time )
- Again both pointers will meet somewhere. And this point will be starting node of the loop.
(As Fastptr in loop, it will move in loop.So, At some point it has to meet slowptr )


Order Complexity : O(n)
Space Complexity:  O(1)



No comments:

Post a Comment