Linked List Cycle II

来源:互联网 发布:金棕榈软件 编辑:程序博客网 时间:2024/05/18 03:43

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

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

解题思路:http://xingxjhui.blog.163.com/blog/static/2155451642014013154023/

/** * 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 NULL;//空结点        ListNode *p=head,*q=head;        while(p && q){            p=p->next;            if(q->next==NULL) return NULL;            q=q->next->next;            if(p==q) break;        }        if(p==NULL || q==NULL ){            return NULL;        }         p=head;        while(p!=q){            p=p->next;            q=q->next;        }        return p;    }};


0 0
原创粉丝点击