Remove Cycle from Linked List
Mediumjavapythonccppjavascript
A singly linked list of N nodes (indices 0 .. N-1) may contain a cycle: the tail's next points at index pos (or -1 for no cycle). Detect the cycle, break it by setting the last node's next to null without deleting any node, then print the list.
Input Format
The first line contains an integer N. The second line contains N space-separated node values. The third line contains an integer pos: the index the tail links back to, or -1.
Output Format
Print the N node values from head to tail after the cycle has been removed, separated by single spaces.
Example 1
Input
4 1 2 3 4 1
Output
1 2 3 4
Explanation: The link from the last node back to index 1 is removed; the values are unchanged.
- 1 <= N <= 100000
- -1 <= pos <= N-1
- -1000000000 <= value <= 1000000000