Python: Detecting Cycle in Linked List

1. Introduction

A common challenge when working with linked lists is cycle detection. A cycle in a linked list means that if you traverse the list indefinitely, you'll find yourself looping through the same set of nodes over and over again. Detecting such cycles is crucial for many algorithms to avoid infinite loops and potential system crashes.

2. Program Overview

Our program aims to detect a cycle in a given linked list. We will:

1. Define a Node class that represents each element in the linked list.

2. Create a LinkedList class with methods to:

- append data to the list.

- create_cycle for intentionally introducing a cycle for testing.

- detect_cycle which will identify if the list contains a cycle.

We'll employ Floyd’s cycle-finding algorithm, often termed as the "Tortoise and the Hare" approach. This technique uses two pointers that move through the list at different speeds.

3. Code Program

class Node:
    def __init__(self, data):
        """Initialize node with data and next as None."""
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        """Initialize linked list with head as None."""
        self.head = None

    def append(self, data):
        """Add data to the end of the linked list."""
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        temp = self.head
        while temp.next:
            temp = temp.next
        temp.next = new_node

    def create_cycle(self, n):
        """Introduce a cycle in the linked list for testing purposes."""
        if self.head is None:
            return
        tail = self.head
        while tail.next:
            tail = tail.next
        node = self.head
        for i in range(n):
            if node is None:
                return
            node = node.next
        tail.next = node

    def detect_cycle(self):
        """Use Floyd's cycle detection algorithm to identify a cycle."""
        tortoise = self.head
        hare = self.head
        while hare and hare.next:
            tortoise = tortoise.next
            hare = hare.next.next
            if tortoise == hare:
                return True
        return False


# Demonstration
llist = LinkedList()
llist.append(1)
llist.append(2)
llist.append(3)
llist.append(4)
llist.append(5)

print(llist.detect_cycle())  # False

llist.create_cycle(2)
print(llist.detect_cycle())  # True

Output:

False
True

4. Step By Step Explanation

1. The Node class represents individual items in our linked list. Each node has data and a reference to the next node.

2. In the LinkedList class, the append method is for adding data to the list. We traverse the list until we find a node with no next node and then add the new data there.

3. The create_cycle method introduces a cycle in our list intentionally by making the next of the tail nodes point back to some node in the list.

4. Our cycle detection relies on the detect_cycle method using the "Tortoise and the Hare" approach. If there's a cycle, the fast-moving hare will eventually catch up to the slower-moving tortoise, and they will both point to the same node. If they do, it confirms a cycle.

Comments