美文网首页
141. Linked List Cycle I and II

141. Linked List Cycle I and II

作者: becauseyou_90cd | 来源:发表于2018-08-01 10:19 被阅读0次

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;
}

}

相关文章

网友评论

      本文标题:141. Linked List Cycle I and II

      本文链接:https://www.haomeiwen.com/subject/wfjlvftx.html