Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
Proof:
StepOne goes one step each time, StepTwo goes two steps each time. We assume that, there are n steps before entering into the cycle, the cycle length is k, the length between cycle begin's node and meeting node is m, then, we have:
StepOne goes n+xk+m steps, StepTwo goes n + yk+m steps, 2*(n+xk+m) = n + yk + m. So (y-2x)k = n + m;
(y-2x-1)k + (k -m) = n. Thus, we know when StepOne goes from the head, and StepTwo goes from the meeting node, they will meet at the cycle begin.
My Answer:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null){
return null;
}
ListNode stepOne = head;
ListNode stepTwo = head;
while(true){
if(stepTwo == null){
return null;
}
stepTwo = stepTwo.next;
if(stepTwo == null){
return null;
}
stepTwo = stepTwo.next;
stepOne = stepOne.next;
if(stepTwo == stepOne){
break;
}
}
stepOne = head;
while(stepOne != stepTwo){
stepOne = stepOne.next;
stepTwo = stepTwo.next;
}
return stepOne;
}
}
題目來源:https://oj.leetcode.com/problems/linked-list-cycle-ii/