Sunday, November 24, 2013

Leetcode Problem : Linked List Cycle


Problem

Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?

Code

bool hasCycle(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
    ListNode *p1 = head;
    if(!p1)
        return false;
    ListNode *p2 = p1->next;
    while(p1 && p2 && p1 != p2){
        p1 = p1->next;
        p2 = p2->next;
        if(p2)
            p2 = p2->next;
    }
    if(p2 && p1)
        return true;
    return false;
}

No comments:

Post a Comment