Instructions
You are given head, the first node of a singly linked list. The list may contain a loop: the next pointer of its last node may point back to an earlier node (or to itself) instead of to null.
If the list has a loop, remove it: find the node whose next points back into the list, and set that next to null. After this, the list contains every node exactly once, in its original order, and ends at that node. If the list has no loop, leave it as it is.
Change the list in place. Your function does not return anything. The judge reads the list from head after your function finishes.
How the input is shown
The input is shown as [values, pos]. values are the node values from the head. pos is the index (counting from 0) of the node that the last node points back to, or -1 when there is no loop. For example, [[5, 8, 2], 1] is 5 -> 8 -> 2, and 2 points back to 8. Your function gets only head, not pos. The output is the list read from head, for example [5, 8, 2].
Note
- Values can repeat, so you cannot find a node by its value.
- Hint: move a slow pointer one step and a fast pointer two steps at a time. If they meet, there is a loop. Put one pointer back at
headand move both one step at a time; they meet at the first node of the loop. Then walk around the loop until you reach the node whosenextis that first node, and cut it there. Take care when the loop starts athead. A set of visited nodes also works, with O(n) extra space.
Examples
Example 1
- Input:
- [[5,8,2,7],1]
- Output:
- [5,8,2,7]
The last node, 7, points back to 8 (index 1). Setting the next of 7 to null removes the loop. The list is now 5 -> 8 -> 2 -> 7.
Example 2
- Input:
- [[4],0]
- Output:
- [4]
The only node points to itself. Setting its next to null leaves a list with one node.
Example 3
- Input:
- [[1,6,9],-1]
- Output:
- [1,6,9]
There is no loop, so the list does not change.
Constraints
0 <=number of nodes<= 60-100 <= Node.val <= 100posis-1or a valid index in the list.
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- [[5,8,2,7],1]
- Expected:
- [5,8,2,7]
- Input:
- [[4],0]
- Expected:
- [4]
- Input:
- [[1,6,9],-1]
- Expected:
- [1,6,9]
Run checks your code against the 3 examples. Submit checks it against all 153 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.