700172. Check If Circular Linked List
Here is the Markdown blog post for the GeeksforGeeks problem "Check If Circular Linked List":
Check If Circular Linked List
Summary
This problem involves checking if a given linked list is circular or not. A circular linked list is one where the last node points back to a previous node, forming a circle instead of ending with a null pointer.
The key concept involved in this problem is understanding how to traverse a linked list and detect whether it forms a cycle or not.
Detailed Explanation
To solve this problem, we can use Floyd's Tortoise and Hare (Cycle Detection) algorithm. This algorithm works by having two pointers, the tortoise and the hare, that move at different speeds through the linked list.
The tortoise moves one step at a time, while the hare moves two steps at a time. If there is no cycle in the linked list, the hare will reach the end of the list. However, if there is a cycle, the hare will eventually meet the tortoise again.
Here's how to implement this algorithm:
- Initialize two pointers,
tortoiseandhare, both pointing to the head of the linked list. - Move the
tortoiseone step at a time, while moving theharetwo steps at a time. - If there is no cycle in the linked list, the
harewill reach the end of the list. In this case, return false (not circular). - If the
haremeets thetortoiseagain, it means we've found a cycle. Return true.
Here's an ASCII art diagram to illustrate this algorithm:
+---+
| 1 |
+---+
|
v
+---+ +---+
| 2 | | 3 |
+---+ +---+
| |
v v
+---+ +---+ +---+
| 4 | | 5 | | 6 |
+---+ +---+ +---+
| | |
v v v
+---+ +---+ +---+ +---+
| ...| | ...| | ...| | ...|
+---+ +---+ +---+ +---+
In this diagram, the tortoise and hare start at node 1. The tortoise moves one step at a time (dashed line), while the hare moves two steps at a time (solid line). If there is no cycle, the hare will reach the end of the list. If there is a cycle, the hare will meet the tortoise again.
The time complexity for this algorithm is O(n), where n is the number of nodes in the linked list. The space complexity is O(1) as we only use a few extra variables to store the pointers.
Optimized Solutions
Java
public boolean isCircular(Node head) {
Node tortoise = head;
Node hare = head;
while (hare != null && hare.next != null) {
tortoise = tortoise.next;
hare = hare.next.next;
if (tortoise == hare) {
return true;
}
}
return false;
}