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

[LeetCode] Linked List Cycle II

时间:2015-06-02 11:20:46      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

Linked List Cycle II

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

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

解题思路:

1、解法1,用set来存储所有已经出现的指针,若出现相同的,这就是环开始的点。比较简单,比再赘述。

2、解法2,双指针法。其中一个指针每次走一步,另一个指针每次走两步。若有环,这两个指针肯定会相遇。当相遇时,其中一个指针又从头开始,另一个指针从相遇的地方开始,两个指针每次都走一步。这两个指针肯定会在环入口相遇。数学上的证明见:http://blog.csdn.net/kangrydotnet/article/details/45154927

/**
 * 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) {
        ListNode* one=head;
        ListNode* two=head;
        while(two!=NULL && two->next!=NULL){
            one=one->next;
            two=two->next->next;
            if(one==two){
                break;
            }
        }
        if(two==NULL || two->next==NULL){
            return NULL;
        }
        one = head;
        while(two!=one){
            one=one->next;
            two=two->next;
        }
        return two;
    }
};



[LeetCode] Linked List Cycle II

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/46324337

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