Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Remove a cycle if present

Detect and remove a cycle from a singly linked list (if one exists) and return the linearized list values.

Python practice15 minLinked ListsIntermediateLast updated March 27, 2026

Problem statement

Given a list of values and pos (cycle position), build a linked list. If pos >= 0 the tail points to the node at index pos, creating a cycle. Detect whether a cycle exists. If it does, remove the cycle so the list becomes linear (tail.next = None). Return the values of the resulting linear list.

Task

Use Floyd's algorithm to detect a cycle, then remove it by finding the cycle start and unlinking the tail. Return the resulting list values.

Examples

Remove a cycle

Input

[3,2,0,-4], 1

Output

[3, 2, 0, -4]

The original list had a cycle; after removal the list becomes linear and converting back yields the same value sequence.

Input format

Two arguments: a Python list of integers and an integer pos. pos is the index (0-based) where the tail connects to form a cycle. pos = -1 means no cycle.

Output format

A Python list of integers representing the list after ensuring there is no cycle (tail.next is None).

Constraints

0 <= len(values) <= 10^5. -1 <= pos < len(values). Aim for O(L) time and O(1) extra space.

Samples

Sample 1

Input

[3,2,0,-4], 1

Output

[3,2,0,-4]

Cycle removed and values returned.