Skip to content
C

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.

Input (stdin)

Output

Run your code to see output here...