Circular Linked List


Why there is a segmentation fault?

This is because your circular linked list is nor being created.
Sample Input

1 2 3 4 5 2 3 -1

You have to create a circular linked list out of this.
1->2->3->4->5 Then next of 5 must be attached to node 2 which was already created.

So what I have to do ?

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.
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

If I encountered 2 again then how will I get its address?

You can make an unordered map with key as the node values and its value as the address of the node.
So whenever a node value gets repeated, you can get the address of that node using the map in O(1) time.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.