Linked List Cycle
Given a linked list, determine if it has a cycle in it.
链表判断是否为环。用快慢指针,快的一次走两步,慢的一次走一步。如果快的能追上慢的那说明有环。
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}
Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
接上题,如果有环就找到环的起点。
数学证明略。还是快慢指针,当它们第一次相遇的时候把慢的那根指针重新指向链表头。它们再次相遇的那个点就是环的起点。
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
slow = head;
while (slow != fast) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
return null;
}