[LeetCode] Linked List Cycle II

203 篇文章 0 订阅

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值