码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Linked List Cycle II

时间:2015-04-05 13:25:38      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:双指针

题目:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

思路分析:
和《Leetcode: Linked List Cycle 》一样还是双指针的方法。

技术分享

一个循环链表如图
slow指针走了S=X+Y
fast指针走了F=X+Y+Z+Y
两个指针相遇。
且有:2S=F,则有X=Z。
所以,从head到环开始的路程 = 从相遇到环开始的路程。
所以,当slow和fast相遇了,我们拿slow从头开始走,fast从相遇的地方开始走,两个都走一步,那么再次相遇必定是环的开始节点。

C++参考代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution
{
public:
    ListNode *detectCycle(ListNode *head)
    {
        if (!head) return nullptr;
        ListNode *slow = head;
        ListNode *fast = head;
        bool hasCycle = false;
        while (fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast)
            {
                hasCycle = true;
                break;
            }
        }
        if (hasCycle)
        {
            slow = head;
            while (slow != fast)
            {
                slow = slow->next;
                fast = fast->next;
            }
            return slow;
        }
        else return nullptr;
    }
};

C#参考代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution
{
    public ListNode DetectCycle(ListNode head)
    {
        if (head == null) return null;
        ListNode slow = head;
        ListNode fast = head;
        bool hasCycle = false;
        while (fast != null && fast.next != null)
        {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast)
            {
                hasCycle = true;
                break;
            }
        }
        if (hasCycle)
        {
            slow = head;
            while (slow != fast)
            {
                slow = slow.next;
                fast = fast.next;
            }
            return slow;
        }
        else return null;
    }
}

Leetcode: Linked List Cycle II

标签:双指针

原文地址:http://blog.csdn.net/theonegis/article/details/44886831

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!