Linked List Cycle II(2014.2.7)

来源:互联网 发布:大学毕业证制作软件 编辑:程序博客网 时间:2024/06/10 12:02
/**
 * 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* p=head;
        ListNode* q=head;
        while(q!=NULL&&q->next!=NULL){
            p=p->next;
            q=q->next->next;
            if(p==q){
                p=head;
                while(p!=q){
                    p=p->next;
                    q=q->next;
                }
                return p;
            }
        }
        return NULL;
    }
};
0 0