0
0
DSA Pythonprogramming~30 mins

Detect Cycle in Linked List Floyd's Algorithm in DSA Python - Build from Scratch

Choose your learning style9 modes available
Detect Cycle in Linked List using Floyd's Algorithm
📖 Scenario: Imagine you have a chain of connected train cars. Sometimes, the chain might loop back on itself, creating a cycle. We want to check if such a loop exists in our chain.
🎯 Goal: You will build a simple linked list and use Floyd's cycle detection algorithm to find out if the list has a cycle.
📋 What You'll Learn
Create a linked list with nodes containing integer values
Add a cycle by connecting the last node to one of the previous nodes
Implement Floyd's cycle detection algorithm using two pointers
Print True if a cycle is found, otherwise False
💡 Why This Matters
🌍 Real World
Detecting cycles in linked lists is important in computer memory management and network routing to avoid infinite loops.
💼 Career
Understanding cycle detection helps in debugging linked list problems and is a common interview question for software engineering roles.
Progress0 / 4 steps
1
Create a linked list with nodes
Create a class called Node with attributes value and next. Then create 5 nodes with values 1, 2, 3, 4, and 5. Link them so that node 1 points to node 2, node 2 points to node 3, node 3 points to node 4, and node 4 points to node 5. Store the first node in a variable called head.
DSA Python
Hint

Define a Node class with value and next. Then create nodes and link them one by one.

2
Create a cycle in the linked list
Create a cycle by setting the next of node5 to node3. This will make the list loop back from node 5 to node 3.
DSA Python
Hint

Set node5.next equal to node3 to create the cycle.

3
Implement Floyd's cycle detection algorithm
Create two pointers called slow and fast and set both to head. Use a while loop that runs while fast and fast.next are not None. Inside the loop, move slow by one step (slow = slow.next) and fast by two steps (fast = fast.next.next). If at any point slow is equal to fast, set a variable has_cycle to True and break the loop. If the loop ends without finding a cycle, set has_cycle to False.
DSA Python
Hint

Use two pointers moving at different speeds. If they meet, a cycle exists.

4
Print if the linked list has a cycle
Print the value of the variable has_cycle.
DSA Python
Hint

Just print the has_cycle variable to see if a cycle was detected.