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 <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;

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");
    printf("\nCreate the loop:\n");
	head->next->next->next->next->next = head->next->next;
    printf("Following statement display the loop:\n");
	printf("\n\nAfter removing the said loop:\n");
    return 0;

Sample Output:

Original singly linked list:
1 2 3 4 5 

Create the loop:
Following statement display the loop:

After removing the said loop:
1 2 3 4 5 

Flowchart :

Flowchart: Remove a loop in a singly linked list.

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?

Follow us on Facebook and Twitter for latest update.