We are given a linked list which contains a cycle. Detect that cycle and break it. Print the linked list after removing the cycle.
Sample case given is:- 1 2 3 4 5 2 3 -1
using fast and slow approach I can’t reach to common point.
We are given a linked list which contains a cycle. Detect that cycle and break it. Print the linked list after removing the cycle.
Sample case given is:- 1 2 3 4 5 2 3 -1
using fast and slow approach I can’t reach to common point.
@nalin1997 In this question you first need to create the circular linked list. Then break it from the point where it forms the loop. Use the Floyd Cycle detection algo as taught in the course.
After breaking the loop you have to print the resulting linked list.
Say If INPUT IS 1 2 3 4 5 2 3 -1
form a linked list 1->2->3->4>5 then you see that 2 has already been visited , so connect the next pointer of 5 to 2. This way you have created the circular linked list . After that just detect the cycle, remove the cycle, print the new linked list.
Hope this helps
How do I need to check every input if it is repeating or not ?
@nalin1997 Maintain a map or a visited array…whenever you see that a node is already visited, connect next pointer of previous node to that node