[LeetCode] Linked List Cycle

http://oj.leetcode.com/problems/linked-list-cycle/

这道题也是随手一写就ac了, 之所以如此快是因为之前写过...

这道题的O(n)解真的挺巧妙的而且也很简单, 两个指针a和b都指表头,a一次走2个结点, b一次走1个结点, 如果链表有环, 则a总有一天会等于b.

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 || head->next == NULL) {
            return false;
        }
        ListNode* p1 = head;
        ListNode* p2 = head->next;
        while (p2 && p1) {
            if (p1 == p2) {
                return true;
            }
            p1 = p1->next;
            p2 = p2->next;
            if (p2) {
                p2 = p2->next;
            }
        }
        return false;
    }
};

 

posted @ 2013-11-05 01:08  NextLife  阅读(147)  评论(0)    收藏  举报