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

LeetCode 142: Linked List Cycle II

时间:2015-04-10 19:52:27      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

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?

思路:

 

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(!head) return NULL;
        ListNode *p = head;
        ListNode *q = head;
        do{
            if(!p||!q) return NULL;
            p = p->next;
            q = q->next;
            if(q) q = q->next;
            else return NULL;
        }while(p!=q);

        p = head;
        while(p!=q){
            p = p->next;
            q = q->next;
        }
        return p;
    }
};

  

LeetCode 142: Linked List Cycle II

标签:

原文地址:http://www.cnblogs.com/xiamaogeng/p/4415257.html

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