[leetcode]Linked List Cycle

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

老题,快慢指针。

/**
 * 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) {
        ListNode *fast = head;
        ListNode *slow = head;
        do {
            if (fast == NULL || fast->next == NULL) return false;
            fast = fast->next->next;
            slow = slow->next;
        } while (fast != slow);
        return true;
    }
};

  

posted @ 2013-12-03 21:21  阿牧遥  阅读(123)  评论(0编辑  收藏  举报