Linked List Cycle II

来源:互联网 发布:园林设计软件有哪些 编辑:程序博客网 时间:2024/06/05 09:33

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

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Follow up:
Can you solve it without using extra space?

public ListNode detectCycle(ListNode head)

这题其实是固定做法,首先先用Linked List Cycle的做法找到第一个相交点,

第二,然后把慢指针返回头指针,然后快慢指针都一步步走next,然后再找到相交点,然后就算是找到了。

给出代码:

    public ListNode detectCycle(ListNode head) {        ListNode one_step = head, two_step = head;        while(one_step != null && two_step != null){            if(two_step.next == null || one_step.next == null){                return null;            }            one_step = one_step.next;            two_step = two_step.next.next;            if(one_step == two_step)                break;        }        if(one_step == null || two_step == null)            return null;        one_step = head;        while(one_step != two_step){            one_step = one_step.next;            two_step = two_step.next;        }        return one_step;    }


0 0