Check if a linked list is Circular Linked List (original) (raw)

Last Updated : 26 Aug, 2024

Try it on GfG Practice redirect icon

Given the **head of a singly linked list, the task is to find if given linked list is circular or not. A linked list is called **circular if its last node points back to its first node.

**Note: The linked list does not contain any internal loops.

**Example:

**Input: LinkedList: 2->4->6->7->5

**Output: true
**Explanation: As shown in figure the first and last node is connected, i.e. 5 -> **2

**Input: LinkedList: 2->4->6->7->5->1

**Output: false
**Explanation: As shown in figure this is not a circular linked list.

Table of Content

[Expected Approach-1] By Traversing each node - O(n) time and O(1) space

The main idea is to traverse through the each node of linked list and check if the **head->next pointer points back to the starting node (**temp). If it does, that means the linked list is circular.

**Code Implementation:

C++ `

// C++ program to check if linked list is circular #include <bits/stdc++.h> using namespace std;

struct Node { int data; Node *next; Node(int x) { data = x; next = NULL; } };

// This function returns true if given linked // list is circular, else false. bool isCircular(Node *head) {

// If the head is null, the linked list is empty,
// so it is circular
if (!head)
    return true;

// Traverse the linked list until either the end
// is reached or the next node is equal to the head
Node *curr = head;
while (curr && curr->next != head)
    curr = curr->next;

// If the end is reached before finding
// the head again, the linked list is not circular
if (!curr)
    return false;

// If the head is found again before reaching
// the end, the linked list is circular
return true;

}

int main() { Node *head = new Node(1); head->next = new Node(2); head->next->next = new Node(3); head->next->next->next = new Node(4);

isCircular(head) ? cout << "Yes\n" : cout << "No\n";

// Making linked list circular
head->next->next->next->next = head;

isCircular(head) ? cout << "Yes\n" : cout << "No\n";

return 0;

}

C

// C program to check if the linked list is circular #include <stdio.h> #include <stdlib.h>

struct Node { int data; struct Node* next; };

struct Node* createNode(int data);

// Function to check if the linked list is circular int isCircular(struct Node* head) { // If head is null, list is empty, circular if (!head) return 1;

struct Node* temp = head;

// Traverse until the end is reached or 
// the next node equals the head
while (head && head->next != temp)
    head = head->next;

// If end reached before finding head again,
// list is not circular
if (!head || !(head->next))
    return 0;

// If head found again, list is circular
return 1;

}

struct Node* createNode(int data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = data; newNode->next = NULL; return newNode; }

int main() { struct Node* head = createNode(1); head->next = createNode(2); head->next->next = createNode(3); head->next->next->next = createNode(4);

// Check if the linked list is circular
isCircular(head) ? printf("Yes\n") : printf("No\n");

// Making the linked list circular
head->next->next->next->next = head;

// Check again if the linked list is circular
isCircular(head) ? printf("Yes\n") : printf("No\n");

return 0;

}

Java

// Java program to check if // linked list is circular

class Node { int data; Node next;

Node(int data) {
    this.data = data;
    this.next = null;
}

}

class GfG {

// Function to check if the linked list is circular
static boolean isCircular(Node head) {
    // If head is null, list is empty, circular
    if (head == null) return true;

    Node temp = head;

    // Traverse until the end is reached or
    // the next node equals the head
    while (head != null && head.next != temp)
        head = head.next;

    // If end reached before finding head again,
    // list is not circular
    if (head == null || head.next == null)
        return false;

    // If head found again, list is circular
    return true;
}

public static void main(String[] args) {
    Node head = new Node(1);
    head.next = new Node(2);
    head.next.next = new Node(3);
    head.next.next.next = new Node(4);

    // Check if the linked list is circular
    System.out.println(isCircular(head) ? "Yes" : "No");

    // Making the linked list circular
    head.next.next.next.next = head;

    // Check again if the linked list is circular
    System.out.println(isCircular(head) ? "Yes" : "No");
}

}

Python

Python program to check if linked list is circular

class Node: def init(self, data): self.data = data self.next = None

Function to check if the linked list is circular

def is_circular(head): # If head is null, list is empty, circular if not head: return True

temp = head

# Traverse until the end is reached or
# the next node equals the head
while head and head.next != temp:
    head = head.next

# If end reached before finding head again,
# list is not circular
if not head or not head.next:
    return False

# If head found again, list is circular
return True

if name == "main": head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4)

# Check if the linked list is circular
print("Yes" if is_circular(head) else "No")

# Making the linked list circular
head.next.next.next.next = head

# Check again if the linked list is circular
print("Yes" if is_circular(head) else "No")

C#

// C# program to check if // linked list is circular using System;

class Node { public int data; public Node next;

public Node(int data) {
    this.data = data;
    this.next = null;
}

}

class GfG {

// Function to check if the linked list is circular
static bool IsCircular(Node head) {
    // If head is null, list is empty, circular
    if (head == null) return true;

    Node temp = head;

    // Traverse until the end is reached or
    // the next node equals the head
    while (head != null && head.next != temp)
        head = head.next;

    // If end reached before finding head again,
    // list is not circular
    if (head == null || head.next == null)
        return false;

    // If head found again, list is circular
    return true;
}

static void Main(string[] args) {
    Node head = new Node(1);
    head.next = new Node(2);
    head.next.next = new Node(3);
    head.next.next.next = new Node(4);

    // Check if the linked list is circular
    Console.WriteLine(IsCircular(head) ? "Yes" : "No");

    // Making the linked list circular
    head.next.next.next.next = head;

    // Check again if the linked list is circular
    Console.WriteLine(IsCircular(head) ? "Yes" : "No");
}

}

JavaScript

// JavaScript program to check if linked list is circular // Class representing a node in the list class Node { constructor(data) { this.data = data; this.next = null; } }

// Function to check if the linked list is circular function isCircular(head) { // If head is null, list is empty, circular if (!head) return true;

let temp = head;

// Traverse until the end is reached or
// the next node equals the head
while (head && head.next !== temp)
    head = head.next;

// If end reached before finding head again,
// list is not circular
if (!head || !head.next)
    return false;

// If head found again, list is circular
return true;

}

// Main part let head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4);

// Check if the linked list is circular console.log(isCircular(head) ? "Yes" : "No");

// Making the linked list circular head.next.next.next.next = head;

// Check again if the linked list is circular console.log(isCircular(head) ? "Yes" : "No");

`

**Time Complexity: O(n), We traverse the linked list in the worst case once, therefore, the time complexity here is linear.
**Auxiliary Space: O(1), We are not using any extra space.

[Expected Approach-2] By Maintaining Slow & Fast Pointers - O(n) time and O(1) space

The idea is to use two pointers, **slow and **fast, to traverse the linked list. The **slow pointer moves one step at a time, while the **fast pointer moves two steps at a time. If the list is circular, the **fast pointer will eventually meet the **slow pointer; otherwise, the **fast pointer will reach NULL indicating the list is not circular.

**Code Implementation:

C++ `

// C++ program to check if linked list is circular

#include <bits/stdc++.h> using namespace std;

struct Node { int data; struct Node *next; Node(int x) { data = x; next = NULL; } };

// Function to check if the linked list is circular bool isCircular(Node *head) { if (!head) { return true; } Node *slow = head; Node *fast = head->next; while (fast && fast->next) { if (slow == fast) { return true; } slow = slow->next; fast = fast->next->next; } return false; }

int main() { struct Node *head = new Node(1); head->next = new Node(2); head->next->next = new Node(3); head->next->next->next = new Node(4);

isCircular(head) ? cout << "Yes\n" : cout << "No\n";

// Making linked list circular
head->next->next->next->next = head;

isCircular(head) ? cout << "Yes\n" : cout << "No\n";

return 0;

}

C

// C program to check if linked list is circular

#include <stdio.h> #include <stdlib.h>

struct Node { int data; struct Node* next; };

struct Node* createNode(int data);

// Function to check if the linked list is circular int isCircular(struct Node* head) { if (!head) return 1;

struct Node *slow = head, *fast = head->next;

// Traverse the linked list with two pointers
while (fast && fast->next) {
    if (slow == fast)
        return 1;
    slow = slow->next;
    fast = fast->next->next;
}
return 0;

}

// Function to create a new node struct Node* createNode(int data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = data; newNode->next = NULL; return newNode; }

int main() { struct Node* head = createNode(1); head->next = createNode(2); head->next->next = createNode(3); head->next->next->next = createNode(4);

// Check if the linked list is circular
isCircular(head) ? printf("Yes\n") : printf("No\n");

// Making the linked list circular
head->next->next->next->next = head;

// Check again if the linked list is circular
isCircular(head) ? printf("Yes\n") : printf("No\n");

return 0;

}

Java

// Java program to check if linked list is circular

class Node { int data; Node next;

Node(int data) {
    this.data = data;
    this.next = null;
}

}

class GfG {

// Function to check if the linked list is circular
static boolean isCircular(Node head) {
    if (head == null)
        return true;

    Node slow = head, fast = head.next;

    // Traverse the linked list with two pointers
    while (fast != null && fast.next != null) {
        if (slow == fast)
            return true;
        slow = slow.next;
        fast = fast.next.next;
    }
    return false;
}

public static void main(String[] args) {
    Node head = new Node(1);
    head.next = new Node(2);
    head.next.next = new Node(3);
    head.next.next.next = new Node(4);

    // Check if the linked list is circular
    System.out.println(isCircular(head) ? "Yes" : "No");

    // Making the linked list circular
    head.next.next.next.next = head;

    // Check again if the linked list is circular
    System.out.println(isCircular(head) ? "Yes" : "No");
}

}

Python

Python program to check if linked list is circular

class Node: def init(self, data): self.data = data self.next = None

Function to check if the linked list is circular

def is_circular(head): if not head: return True

slow = head
fast = head.next
while fast and fast.next:
    if slow == fast:
        return True
    slow = slow.next
    fast = fast.next.next

return False

if name == "main": head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4)

# Check if the linked list is circular
print("Yes" if is_circular(head) else "No")

# Making the linked list circular
head.next.next.next.next = head

# Check again if the linked list is circular
print("Yes" if is_circular(head) else "No")

C#

// C# program to check if linked list is circular

using System;

class Node { public int data; public Node next;

public Node(int data) {
    this.data = data;
    this.next = null;
}

}

class GfG {

// Function to check if the linked list is circular
static bool IsCircular(Node head) {
    if (head == null) {
        return true;
    }
    Node slow = head;
    Node fast = head.next;
    while (fast != null && fast.next != null) {
        if (slow == fast) {
            return true;
        }
        slow = slow.next;
        fast = fast.next.next;
    }
    return false;
}

static void Main(string[] args) {
    Node head = new Node(1);
    head.next = new Node(2);
    head.next.next = new Node(3);
    head.next.next.next = new Node(4);

    // Check if the linked list is circular
    Console.WriteLine(IsCircular(head) ? "Yes" : "No");

    // Making the linked list circular
    head.next.next.next.next = head;

    // Check again if the linked list is circular
    Console.WriteLine(IsCircular(head) ? "Yes" : "No");
}

}

JavaScript

// JavaScript program to check if linked list is circular

class Node { constructor(data) { this.data = data; this.next = null; } }

// Function to check if the linked list is circular function isCircular(head) { if (!head) { return true; } let slow = head; let fast = head.next; while (fast && fast.next) { if (slow === fast) { return true; } slow = slow.next; fast = fast.next.next; } return false; }

// Main part let head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4);

// Check if the linked list is circular console.log(isCircular(head) ? "Yes" : "No");

// Making the linked list circular head.next.next.next.next = head;

// Check again if the linked list is circular console.log(isCircular(head) ? "Yes" : "No");

`

**Time Complexity: O(n), We traverse the linked list in the worst case once, therefore, the time complexity here is linear.
**Auxiliary Space: O(1), We use two Node pointers, slow and fast, so the extra space is constant.