Cycle Detection in linked list
We are having two nodes .
1 will go only one step and another for two and if they met means there is cycle else not
Code:
/*
Detect a cycle in a linked list. Note that the head pointer may be 'null' if the list is empty.
A Node is defined as:
class Node {
int data;
Node next;
}
*/
boolean hasCycle(Node head) {
if (head == null){
return false;
}
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if (slow == fast){
return true;
}
}
return false;
}
1 will go only one step and another for two and if they met means there is cycle else not
Code:
/*
Detect a cycle in a linked list. Note that the head pointer may be 'null' if the list is empty.
A Node is defined as:
class Node {
int data;
Node next;
}
*/
boolean hasCycle(Node head) {
if (head == null){
return false;
}
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if (slow == fast){
return true;
}
}
return false;
}
0 Comments:
Post a Comment