Given a linked list, return the node where the cycle begins. If there is no cycle, return
Have you met this question in a real interview? null
.
Yes
Example
Given -21->10->4->5, tail connects to node index 1,返回10
Challenge
public class Solution {
Follow up:
Can you solve it without using extra space?
Can you solve it without using extra space?
/**
* @param head: The first node of linked list.
* @return: The node where the cycle begins.
* if there is no cycle, return null
*/
public ListNode detectCycle(ListNode head) {
// write your code here
if(head == null || head.next == null) return null;
ListNode slow = head, fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(fast == slow) break;
}
if(fast != slow){
return null;
}
slow = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return fast;
}
}
No comments:
Post a Comment