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

leetcode142 Linked List Cycle II

时间:2016-05-09 20:14:56      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

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.

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

note:

开始时,两指针都指向head,之后再快步慢步走;

假设head为A,环起始点为B,两指针相遇点为C,则LAB=LBC+n环周长;

 

leetcode142 Linked List Cycle II

标签:

原文地址:http://www.cnblogs.com/jsir2016bky/p/5475066.html

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