Skip to main content

Finding loop in a linked list.

KANISHKA GUPTA
EditReport

Finding a Loop in a Linked List

Problem Description​

In a linked list, a loop occurs when a node's next pointer points back to a previous node, creating a cycle. Detecting a loop is crucial, as it can lead to infinite traversals and memory issues. The goal is to determine whether a loop exists in the linked list and, if so, identify the node where the loop begins.

Video Explanation​

Approach​

One of the most efficient methods for detecting a loop in a linked list is Floyd's Cycle-Finding Algorithm, also known as the "Tortoise and Hare" algorithm.

Steps:​

  1. Initialization: Use two pointers, slow and fast. The slow pointer moves one step at a time, while the fast pointer moves two steps at a time.

  2. Traversal:

    • Start both pointers at the head of the linked list.
    • Move slow by one node and fast by two nodes in each iteration.
    • If fast reaches the end of the list (null), there is no loop.
    • If slow equals fast, a loop exists.
  3. Finding the Start of the Loop:

    • Once a loop is detected, to find the starting node of the loop:
      • Move one pointer back to the head of the list and keep the other at the meeting point.
      • Move both pointers one step at a time; the node where they meet is the start of the loop.

Implementation​

Solutions​

#include <iostream>

class Node {
public:
int value;
Node* next;

Node(int val) : value(val), next(nullptr) {}
};

class LinkedList {
public:
Node* head;

LinkedList() : head(nullptr) {}

// Detect loop using Floyd's Cycle-Finding Algorithm
Node* detectLoop() {
Node* slow = head;
Node* fast = head;

// Phase 1: Detect loop
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;

if (slow == fast) { // Loop detected
break;
}
}

// No loop
if (fast == nullptr || fast->next == nullptr) {
return nullptr;
}

// Phase 2: Find the start of the loop
slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}

return slow; // Start of the loop
}

// Method to create a loop for testing
void createLoop(int loopStartIndex) {
Node* loopStartNode = head;
Node* lastNode = head;
int index = 0;

// Find the loop start node
while (index < loopStartIndex) {
loopStartNode = loopStartNode->next;
index++;
}

// Find the last node
while (lastNode->next != nullptr) {
lastNode = lastNode->next;
}

// Create the loop
lastNode->next = loopStartNode;
}
};

// Example usage
int main() {
LinkedList ll;
ll.head = new Node(1);
ll.head->next = new Node(2);
ll.head->next->next = new Node(3);
ll.head->next->next->next = new Node(4);
ll.head->createLoop(1); // Creating a loop back to node with value 2

Node* loopStart = ll.detectLoop();
if (loopStart != nullptr) {
std::cout << "Loop detected at node with value: " << loopStart->value << std::endl;
} else {
std::cout << "No loop detected." << std::endl;
}

return 0;
}
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

đŸ’Ŧ Discuss this page

Have a question or spot something confusing in "Finding loop in a linked list."? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.