VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-linked-list-is-circular-linked-list/

⇱ Check if a linked list is Circular Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a linked list is Circular Linked List

Last Updated : 26 Aug, 2024

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

👁 Image

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

👁 Image

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

[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:


Output
No
Yes

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:


Output
false

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.

Comment