Linked List Cycle II

2015-11-30  本文已影响64人  ab409

Linked List Cycle II


今天是一道有关链表的题目,是Linked List Cycle(回复022查看)的升级版,来自LeetCode,难度为Medium,Acceptance为31.4%

题目如下


Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note:
Do not modify the linked list.
Follow up:
Can you solve it without using extra space?

解题思路及代码见阅读原文

回复0000查看更多题目

解题思路


首先,该题是Linked List Cycle(回复022查看)的升级版。在Linked List Cycle一题中,只需要求是否有环,比较容易。 只需用两个指针,一快一慢,快指针一次走两步,慢指针一次走一步。

然后,在该题中要进一步求链表开始的节点。这里需要一点数学计算,如图所示:

链表计算.png

有了上面的计算过程,下面我们就可以按照以下思路求该节点。

最后,我们来看代码。

代码如下


Java版

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                ListNode slow2 = head;
                while(slow2 != slow){
                    slow2 = slow2.next;
                    slow = slow.next;
                }
                return slow2;
            }
        }
        return null;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读