how to check whether a linked list is circular in c?

28 Dec 2022 Balmiki Mandal 0 C Programming

How to Check Whether a Linked List is Circular in C?

If you're working with linked lists in C, it's essential to be able to determine whether a linked list contains a cycle (i.e., it's circular) or not. Here's a step-by-step guide on how to do it:

Understanding Circular Linked Lists:

A circular linked list is a type of linked list where the last node points back to the first node, forming a loop.

Using the Floyd's Cycle Detection Algorithm:

The Floyd's Cycle Detection Algorithm, also known as the "tortoise and hare" algorithm, is a popular method for detecting cycles in a linked list.

Algorithm Overview:

  • Initialize two pointers, slow and fast, both pointing to the head of the linked list.
  • Move the slow pointer one step at a time and the fast pointer two steps at a time.
  • If there is a cycle, eventually the fast pointer will catch up to the slow pointer.

Checking for a Cycle:

Implement the Floyd's Cycle Detection Algorithm in C as follows:

int isCircular(struct Node* head) {
    struct Node *slow = head, *fast = head;
    while (slow && fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
        if (slow == fast)
            return 1; // Circular Linked List
    }
    return 0; // Not a Circular Linked List
}

Using the Function:

Call the isCircular() function with the head of your linked list as an argument.

 

 

if (isCircular(head))
    printf("The linked list is circular.");
else
    printf("The linked list is not circular.");

Example:

Consider the linked list: 1 -> 2 -> 3 -> 4 -> 2 (where 4 points back to 2, creating a loop).

 

struct Node* head = createLinkedList(); // Function to create linked list
if (isCircular(head))
    printf("The linked list is circular.");
else
    printf("The linked list is not circular.");

 

For further information and examples, Please visit [C-Programming From Scratch to Advanced 2023-2024

Conclusion:

With the Floyd's Cycle Detection Algorithm, you can efficiently check whether a linked list is circular or not in C.

Additional Considerations:

Ensure that you handle cases where the linked list is empty or contains only one node separately.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.