Code
Java
// Initialize slow & fast pointers
ListNode slow = head;
ListNode fast = head;
/**
* Change this condition to fit specific problem.
* Attention: remember to avoid null-pointer error
**/
while (slow != null && fast != null && fast.next != null) {
slow = slow.next; // move slow pointer one step each time
fast = fast.next.next; // move fast pointer two steps each time
if (slow == fast) { // change this condition to fit specific problem
return true;
}
}
return false; // change return value to fit specific problem
Go
// Initialize slow & fast pointers
var slow *ListNode = head
var fast *ListNode = head
/**
* Change this condition to fit specific problem.
* Attention: remember to avoid null-pointer error
**/
for slow != nil && fast != nil && fast.Next != nil {
slow = slow.Next // move slow pointer one step each time
fast = fast.Next.Next // move fast pointer two steps each time
if slow == fast { // change this condition to fit specific problem
return true
}
}
return false // change return value to fit specific problem
댓글 영역