LeetCode-Linked List Cycle

Given a linked list, determine if it has a cycle in it.

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(head==NULL)return false;
        ListNode* p1=head,*p2=head;
        
        while(true){
            p1=p1->next;
            if(p1==NULL)return false;
            p2=p2->next;
            if(p2==NULL)return false;
            p2=p2->next;
            if(p2==NULL)return false;
            if(p1==p2)return true;
        }
    }
};

 

posted @ 2013-11-13 10:00  懒猫欣  阅读(119)  评论(0编辑  收藏  举报