Detect and Remove Loop in Linked List
Last Updated :
28 Dec, 2024
Given the head of a linked list that may contain a loop. A loop means that the last node of the linked list is connected back to a node in the same list. The task is to Remove the loop from the linked list (if it exists).
Example:
Input:

Output: 1 -> 3 -> 4
Explanation: The Loop is removed from the above example.
Input:

Output: 1 -> 8 -> 3 -> 4
Explanation: There is no Loop in the above example.
[Naive Approach] Detect and Remove Loop using Hashing – O(n) Time and O(n) Space:
The idea is to start traversing the Linked List from head node and while traversing insert each node into the HashSet. Also, maintain a prev pointer which points to the previous node of the current node. If there is a loop present in the Linked List, there will be a node which will be already present in the hash set.
- If there is a node which is already present in the HashSet, then update the next pointer of prev to NULL to remove the loop from the linked list.
- else, if there is no node which is already present in the HashSet , then there is no loop in the linked list.
Below is the implementation of the algorithm:
C++
// C++ code to detect and remove loop in
// linked list using hashing
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
Node(int x) {
data = x;
next = nullptr;
}
};
void printList(Node* curr) {
while (curr != nullptr) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
// Function to detect and remove loop in
// a linked list
void removeLoop(Node* head) {
// hash set to hash addresses of
// the linked list nodes
unordered_set<Node*> st;
// pointer to prev node
Node* prev = nullptr;
while (head != nullptr) {
// if node not present in the map,
// insert it in the map
if (st.find(head) == st.end()) {
st.insert(head);
prev = head;
head = head->next;
}
// if present, it is a cycle, make the
// last node's next pointer NULL
else {
prev->next = nullptr;
break;
}
}
}
int main() {
Node* head = new Node(50);
head->next = new Node(20);
head->next->next = new Node(15);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(10);
head->next->next->next->next->next = head->next->next;
removeLoop(head);
printList(head);
return 0;
}
Java
// Java code to detect and remove loop in linked
// list using hashing
import java.util.*;
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
class GfG {
static void printList(Node curr) {
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
}
// Function to detect and remove
// loop from linked list
static void removeLoop(Node head) {
HashSet<Node> st = new HashSet<Node>();
Node prev = null;
while (head != null) {
// If we have already seen this node in
// hash set, it means there is a cycle.
// Set the next of the previous pointer
// to null to remove the cycle.
if (st.contains(head)) {
prev.next = null;
return;
}
// If we are seeing the node for the first time,
// insert it in hash set.
else {
st.add(head);
prev = head;
head = head.next;
}
}
}
public static void main(String[] args) {
Node head = new Node(50);
head.next = new Node(20);
head.next.next = new Node(15);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(10);
head.next.next.next.next.next = head.next.next;
removeLoop(head);
printList(head);
}
}
Python
# Python code to detect and remove loop in linked
# list using hashing
class Node:
def __init__(self, x):
self.data = x
self.next = None
def printList(curr):
# Function to print the linked list
while curr:
print(curr.data, end=' ')
curr = curr.next
print()
def removeLoop(head):
# Function to detect and remove loop from linked list
nodeSet = set()
prev = None
while head:
# If node is already in the set, remove the loop
if head in nodeSet:
prev.next = None
return
# Add node to the set and move forward
nodeSet.add(head)
prev = head
head = head.next
if __name__ == "__main__":
head = Node(50)
head.next = Node(20)
head.next.next = Node(15)
head.next.next.next = Node(4)
head.next.next.next.next = Node(10)
head.next.next.next.next.next = head.next.next
removeLoop(head)
printList(head)
C#
// C# code to detect and remove loop in a
// linked list using hashing
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node next;
public Node(int x) {
data = x;
next = null;
}
}
class GfG {
static void PrintList(Node curr) {
while (curr != null) {
Console.Write(curr.data + " ");
curr = curr.next;
}
}
// Function to detect and remove loop from linked list
static void removeLoop(Node head) {
HashSet<Node> st = new HashSet<Node>();
Node prev = null;
while (head != null) {
// If we have already seen this node in
// hash set, it means there is a cycle.
// Set the next of the previous pointer
// to null to remove the cycle.
if (st.Contains(head)) {
prev.next = null;
return;
}
// If we are seeing the node for the first time,
// insert it in hash set.
else {
st.Add(head);
prev = head;
head = head.next;
}
}
}
static void Main(string[] args) {
Node head = new Node(50);
head.next = new Node(20);
head.next.next = new Node(15);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(10);
head.next.next.next.next.next = head.next.next;
removeLoop(head);
PrintList(head);
}
}
JavaScript
// JavaScript code to detect and remove loop in a
// linked list using hashing
class Node {
constructor(x) {
this.data = x;
this.next = null;
}
}
function printList(curr) {
while (curr != null) {
console.log(curr.data + " ");
curr = curr.next;
}
}
// Function to detect and remove loop from linked list
function removeLoop(head) {
let st = new Set();
let prev = null;
while (head != null) {
// If node is already in the set, remove the loop
if (st.has(head)) {
prev.next = null;
return;
}
// Add node to the set and move forward
st.add(head);
prev = head;
head = head.next;
}
}
head = new Node(50);
head.next = new Node(20);
head.next.next = new Node(15);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(10);
head.next.next.next.next.next = head.next.next;
removeLoop(head);
printList(head);
Time Complexity: O(n), Where n is the number of nodes in the linked list.
Auxiliary Space: O(n), Where n is the number of nodes in the linked list(due to hashing).
[Efficient Approach] Using Floyd’s Cycle Detection Algorithm – O(n) Time and O(1) Space:
This approach can be divided into two parts:
- Use two pointers, slow and fast and initialize them with the head of the linked list.
- Move the fast pointer forward by two nodes and move the slow pointer forward by one node.
- If the slow and fast pointer points to the same node, loop is found.
- Else if the fast pointer reaches NULL, then no loop is found.
- Else repeat the above steps till we reach the end of the linked list or a loop is found.
2. Remove Loop in Linked List (if any):
The idea is similar to finding the starting node of Loop in a Linked List. For this, we will point the slow pointer to head node and fast pointer will remain at its position. Both slow and fast pointers move one step ahead until fast->next is not equals to slow->next. When slow->next equals to fast->next we can easily point fast->next to NULL to remove the loop.
Below is the implementation of the algorithm:
C++
// C++ program Using Floyd's Cycle Detection Algorithm
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *next;
Node(int x) {
data = x;
next = nullptr;
}
};
void printList(Node *curr) {
while (curr != nullptr) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
// Function to detect and remove loop in a linked list that
// may contain loop
void removeLoop(Node *head) {
// If list is empty or has only one node without loop
if (head == nullptr || head->next ==nullptr)
return;
Node *slow = head, *fast = head;
// Move slow and fast 1 and 2 steps ahead respectively.
slow = slow->next;
fast = fast->next->next;
// Search for loop using slow and fast pointers
while (fast && fast->next) {
if (slow == fast)
break;
slow = slow->next;
fast = fast->next->next;
}
// If loop exists
if (slow == fast) {
slow = head;
// this check is needed when slow and fast both meet
// at the head of the LL eg: 1->2->3->4->5 and then
// 5->next = 1 i.e the head of the LL
if (slow == fast)
while (fast->next != slow)
fast = fast->next;
else {
while (slow->next != fast->next) {
slow = slow->next;
fast = fast->next;
}
}
// since fast->next is the looping point
fast->next = nullptr;
}
}
int main() {
Node *head = new Node(50);
head->next = new Node(20);
head->next->next = new Node(15);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(10);
head->next->next->next->next->next = head;
removeLoop(head);
printList(head);
return 0;
}
C
// C program Using Floyd's Cycle Detection Algorithm
#include <stdio.h>
#include <stdlib.h>
struct Node {
int key;
struct Node *next;
};
void printList(struct Node *curr) {
while (curr != NULL) {
printf("%d ", curr->key);
curr = curr->next;
}
printf("\n");
}
// Function to detect and remove loop in a linked list that
// may contain loop
void removeLoop(struct Node *head) {
// If list is empty or has only one node without loop
if (head == NULL || head->next == NULL)
return;
struct Node *slow = head, *fast = head;
// Move slow and fast 1 and 2 steps ahead respectively.
slow = slow->next;
fast = fast->next->next;
// Search for loop using slow and fast pointers
while (fast && fast->next) {
if (slow == fast)
break;
slow = slow->next;
fast = fast->next->next;
}
// If loop exists
if (slow == fast) {
slow = head;
// this check is needed when slow and fast both meet
// at the head of the LL eg: 1->2->3->4->5 and then
// 5->next = 1 i.e the head of the LL
if (slow == fast)
while (fast->next != slow)
fast = fast->next;
else {
while (slow->next != fast->next) {
slow = slow->next;
fast = fast->next;
}
}
// since fast->next is the looping point
// remove loop
fast->next = NULL;
}
}
struct Node *createNode(int key) {
struct Node *curr =
(struct Node *)malloc(sizeof(struct Node));
curr->key = key;
curr->next = NULL;
return curr;
}
int main() {
struct Node *head = createNode(50);
head->next = head;
head->next = createNode(20);
head->next->next = createNode(15);
head->next->next->next = createNode(4);
head->next->next->next->next = createNode(10);
head->next->next->next->next->next = head;
removeLoop(head);
printList(head);
return 0;
}
Java
// Java program Using Floyd's Cycle Detection Algorithm
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function that detects loop in the list
static void removeLoop(Node node) {
// If list is empty or has only one node
// without loop
if (node == null || node.next == null)
return;
Node slow = node, fast = node;
// Move slow and fast 1 and 2 steps
// ahead respectively.
slow = slow.next;
fast = fast.next.next;
// Search for loop using slow and fast pointers
while (fast != null && fast.next != null) {
if (slow == fast)
break;
slow = slow.next;
fast = fast.next.next;
}
// If loop exists
if (slow == fast) {
slow = node;
if (slow != fast) {
while (slow.next != fast.next) {
slow = slow.next;
fast = fast.next;
}
// since fast->next is the looping point
// remove loop
fast.next = null;
}
// This case is added if fast and slow
// pointer meet at first position.
else {
while(fast.next != slow) {
fast = fast.next;
}
fast.next = null;
}
}
}
static void printList(Node curr) {
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
}
public static void main(String[] args) {
Node head = new Node(50);
head.next = new Node(20);
head.next.next = new Node(15);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(10);
head.next.next.next.next.next = head.next.next;
removeLoop(head);
printList(head);
}
}
Python
# Python program Using Floyd's Cycle Detection Algorithm
class Node:
def __init__(self, x):
self.data = x
self.next = None
# Function to remove the loop from the linked list
def removeLoop(head):
# If the list is empty or has only one node
# without a loop
if head is None or head.next is None:
return
slow = head
fast = head
# Move slow and fast pointers; slow moves 1 step,
# fast moves 2 steps
while slow and fast and fast.next:
slow = slow.next
fast = fast.next.next
# If slow and fast meet, a loop is detected
if slow == fast:
slow = head
# Move slow and fast pointers to find the node
# where the loop starts
while slow != fast:
slow = slow.next
fast = fast.next
# Traverse the loop to find the node where the
# loop ends and remove it
while fast.next != slow:
fast = fast.next
fast.next = None
return
def printList(curr):
while curr:
print(curr.data, end=' ')
curr = curr.next
print()
if __name__ == "__main__":
# Create a linked list with a loop:
# 50 -> 20 -> 15 -> 4 -> 10 -> (points back to 15)
head = Node(50)
head.next = Node(20)
head.next.next = Node(15)
head.next.next.next = Node(4)
head.next.next.next.next = Node(10)
# Creating a loop by pointing the last
# node (10) to the third node (15)
head.next.next.next.next.next = head.next.next
# Remove the loop from the linked list
removeLoop(head)
printList(head)
C#
// C# program Using Floyd's Cycle Detection Algorithm
class Node {
public int data;
public Node next;
public Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function that detects loop in the list
static void removeLoop(Node node) {
// If list is empty or has only one node
// without loop
if (node == null || node.next == null)
return;
Node slow = node, fast = node;
// Move slow and fast 1 and 2 steps
// ahead respectively.
slow = slow.next;
fast = fast.next.next;
// Search for loop using slow and fast pointers
while (fast != null && fast.next != null) {
if (slow == fast)
break;
slow = slow.next;
fast = fast.next.next;
}
// If loop exists
if (slow == fast) {
slow = node;
if (slow != fast) {
while (slow.next != fast.next) {
slow = slow.next;
fast = fast.next;
}
// since fast->next is the looping point
// remove loop
fast.next = null;
}
// This case is added if fast and slow pointer
// meet at first position.
else {
while (fast.next != slow) {
fast = fast.next;
}
fast.next = null;
}
}
}
static void printList(Node curr) {
while (curr != null) {
System.Console.Write(curr.data + " ");
curr = curr.next;
}
}
static void Main(string[] args) {
Node head = new Node(50);
head.next = new Node(20);
head.next.next = new Node(15);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(10);
head.next.next.next.next.next = head.next.next;
removeLoop(head);
printList(head);
}
}
JavaScript
// JavaScript program Using Floyd's Cycle Detection Algorithm
class Node {
constructor(x) {
this.data = x;
this.next = null;
}
}
// Function to detect and remove loop in the linked list
function removeLoop(node) {
// If list is empty or has only one node without loop
if (node == null || node.next == null) return;
let slow = node, fast = node;
// Move slow and fast 1 and 2 steps
// ahead respectively
slow = slow.next;
fast = fast.next.next;
// Search for loop using slow and fast pointers
while (fast != null && fast.next != null) {
if (slow == fast) break;
slow = slow.next;
fast = fast.next.next;
}
// If loop exists
if (slow == fast) {
slow = node;
// If the loop starts at the head of the list
if (slow != fast) {
while (slow.next != fast.next) {
slow = slow.next;
fast = fast.next;
}
// Remove the loop
fast.next = null;
} else {
// Special case when loop starts at the head
while (fast.next != slow) {
fast = fast.next;
}
fast.next = null;
}
}
}
function printList(curr) {
let result = [];
while (curr != null) {
result.push(curr.data);
curr = curr.next;
}
console.log(result.join(' '));
}
let head = new Node(50);
head.next = new Node(20);
head.next.next = new Node(15);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(10);
head.next.next.next.next.next = head.next.next;
removeLoop(head);
printList(head);
Time Complexity: O(n), where n is the number of nodes in the Linked List
Auxiliary Space: O(1)
For more details about the working & proof of this algorithm, Please refer to this article, How does Floyd’s Algorithm works.
Similar Reads
Detect and Remove Loop in Linked List
Given the head of a linked list that may contain a loop. A loop means that the last node of the linked list is connected back to a node in the same list. The task is to Remove the loop from the linked list (if it exists). Example: Input: Output: 1 -> 3 -> 4 Explanation: The Loop is removed fro
15 min read
Detect loop or cycle in a linked list
Given a singly linked list, check if the linked list has a loop (cycle) or not. A loop means that the last node of the linked list is connected back to a node in the same list. Examples: Input: head: 1 -> 3 -> 4 -> 3Output: true Input: head: 1 -> 8 -> 3 -> 4 -> NULL Output: fals
13 min read
Find first node of loop in a linked list
Given the head of a linked list that may contain a loop. A loop means that the last node of the linked list is connected back to a node in the same list. The task is to find the Starting node of the loop in the linked list if there is no loop in the linked list return -1. Example: Input: Output: 3Ex
14 min read
Write a function to delete a Linked List
Given a linked list, the task is to delete the linked list completely. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> NULLOutput: NULLExplanation: Linked List is Deleted.Input: head: 1 -> 12 -> 1 -> 4 -> 1 -> NULLOutput: NULLExplanation: Linked List is Deleted. Table o
9 min read
Detect Cycle in a Linked List using Map
Given a Linked List, check if the linked list has a loop or not.There are various methods shown here: Detect Cycle in Linked List Example Input: 20->4->54->6->NULL Output: No loop is detected. Explanation: While traversing the linked list, we reach the end of the linked list. Therefore,
7 min read
Count Occurrences in a Linked List
Given a singly linked list and a key, the task is to count the number of occurrences of the given key in the linked list. Example : Input : head: 1->2->1->2->1->3->1 , key = 1Output : 4 Explanation: key equals 1 has 4 occurrences. Input : head: 1->2->1->2->1, key = 3Out
9 min read
Deletion at end (Removal of last node) in a Linked List
Given a linked list, the task is to delete the last node of the given linked list. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULLOutput: 1 -> 2 -> 3 -> 4 -> NULL Explanation: The last node of the linked list is 5, so 5 is deleted. Input: 3 -> 12 -> 15-> NULLOutp
8 min read
First non-repeating in a linked list
Given a linked list, find its first non-repeating integer element. Examples: Input : 10->20->30->10->20->40->30->NULLOutput :First Non-repeating element is 40.Input :1->1->2->2->3->4->3->4->5->NULLOutput :First Non-repeating element is 5.Input :1->1
12 min read
Find a peak element in Linked List
Given a linked list of integers, the task is to find a peak element in the given linked list. An element is a peak, if it is greater than or equals to its neighbors. For boundary elements, consider only one neighbor. Examples: Input : List = {1 -> 6 -> 8 -> 4 -> 12} Output : 8Explanation
8 min read
XOR Linked List: Remove last node of the Linked List
Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4<–>7<–>9<–>7Output: 4<–>7<–>9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4<–>7<–>9 Input: 10Output: List is empt
15+ min read
Remove every k-th node of the linked list
Given a singly linked list, the task is to remove every kth node of the linked list. Assume that k is always less than or equal to the length of the Linked List. Examples : Input: LinkedList: 1 -> 2 -> 3 -> 4 -> 5 -> 6, k = 2Output: 1 -> 3 -> 5 Explanation: After removing every
9 min read
Deletion at beginning (Removal of first node) in a Linked List
Given a linked list, The task is to remove the first node from the given linked list. Examples: Input : head : 3 -> 12 -> 15 -> 18 -> NULLOutput : 12 -> 15 -> 18 -> NULL Input : head : 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> NULLOutput : 4 -> 6 -> 8 -> 33 -
6 min read
Rearrange a given linked list in-place
Given a singly linked list L0 -> L1 -> … -> Ln-1 -> Ln. Rearrange the nodes in the list so that the newly formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 ... You are required to do this in place without altering the nodes' values. Examples: Input: 1 -> 2 -> 3 -
10 min read
Find length of loop/cycle in given Linked List
Given the head of a linked list. The task is to find the length of the loop in the linked list. If the loop is not present return 0. Examples: Input: head: 25 -> 14 -> 19 -> 33 -> 10 -> 21 -> 39 ->90 ->58 -> 45 -> 33Output: 7Explanation: The loop is present in the below
12 min read
Remove Duplicates from an Unsorted Linked List
Given an unsorted linked list containing n nodes, the task is to remove duplicate nodes while preserving the original order. Examples: Input: 12 -> 11 -> 12 -> 21 -> 41 -> 43 -> 21 Output: 12 -> 11 -> 21 -> 41 -> 43 Explanation: The second occurrence of 12 (the one afte
14 min read
Deletion in Linked List
Deleting a node in a Linked List is an important operation and can be done in three main ways: removing the first node, removing a node in the middle, or removing the last node. In this article, we will explore deletion operation on Linked List for all the above scenarios. Types of Deletion in Linke
15+ min read
Remove Nth node from end of the Linked List
Given a linked list. The task is to remove the Nth node from the end of the linked list. Examples: Input : LinkedList = 1 ->2 ->3 ->4 ->5 , N = 2Output : 1 ->2 ->3 ->5Explanation: Linked list after deleting the 2nd node from last which is 4, is 1 ->2 ->3 ->5 Input : Lin
15+ min read
Given a linked list of line segments, remove middle points
Given a linked list of coordinates where adjacent points either form a vertical line or a horizontal line. Delete points from the linked list which are in the middle of a horizontal or vertical line. Examples: Input: (0,10)->(1,10)->(5,10)->(7,10) | (7,5)->(20,5)->(40,5) Output: Linke
14 min read
Search an element in a Doubly Linked List
Given a Doubly linked list(DLL) containing n nodes and an integer x, the task is to find the position of the integer x in the doubly linked list. If no such position found then print -1. Examples: Input: Linked List = 18 <-> 15 <-> 8 <-> 9 <-> 14, x = 8 Output: 3 Explanation:
7 min read