C Exercises: Remove a loop in a singly linked list
C Singly Linked List : Exercise-14 with Solution
Write a C program to detect and remove a loop in a singly linked list.
Sample Solution:
C Code:
#include<stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* newNode(int data) {
struct Node* node = (struct Node*) malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}
// Function to detect and remove loop in a linked list
void detect_and_remove_Loop(struct Node* head) {
struct Node* slow = head;
struct Node* fast = head;
// Use Floyd's cycle-finding algorithm to detect a loop
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) break;
}
// If a loop is detected
if (slow == fast) {
slow = head;
while (slow->next != fast->next) {
slow = slow->next;
fast = fast->next;
}
// Break the loop by setting the next pointer of the loop node to NULL
fast->next = NULL;
}
}
// Function to print a linked list
void displayList(struct Node* head) {
while (head) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
struct Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);
printf("Original singly linked list:\n");
displayList(head);
printf("\nCreate the loop:\n");
head->next->next->next->next->next = head->next->next;
printf("Following statement display the loop:\n");
printf("displayList(head);");
//displayList(head);
printf("\n\nAfter removing the said loop:\n");
detect_and_remove_Loop(head);
displayList(head);
return 0;
}
Sample Output:
Original singly linked list: 1 2 3 4 5 Create the loop: Following statement display the loop: displayList(head); After removing the said loop: 1 2 3 4 5
Flowchart :

C Programming Code Editor:
Previous: Combine two sorted singly linked lists.
Next: Check if a singly linked list is palindrome or not.
What is the difficulty level of this exercise?
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join