141. Linked List Cycle I and II

https://leetcode.com/problems/linked-list-cycle/description/
https://leetcode.com/problems/linked-list-cycle-ii/description/

解题思路:

  1. 用slow and fast来判断是否他们有相遇时候。
  2. 当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;
}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容