https://leetcode.com/problems/linked-list-cycle/description/
https://leetcode.com/problems/linked-list-cycle-ii/description/
解题思路:
- 用slow and fast来判断是否他们有相遇时候。
- 当slow == fast,我们需要用使head == slow为了寻找begin node
代码:
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return false;
ListNode slow = head, fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast)
return true;
}
return false;
}
}
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head, fast = head, meet = null;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
while(head != slow){
head = head.next;
slow = slow.next;
}
return head;
}
}
return null;
}
}