1. 程式人生 > >LeetCode | Linked List Cycle(判斷連結串列是否有環)

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?

題目解析:

判斷是否有環,只需要快慢指標即可。注意考慮程式的健壯性。

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == NULL || head->next == NULL)
            return false;
        ListNode *p,*q;
        p = head;
        q = head->next;
        while(q->next && p!=q){
            p = p->next;
            if(q->next->next == NULL )
                return false;
            q = q->next->next;
        }
        if(p == q)
            return true;
        else
            return false;
    }
};