LeetCode OJ - 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) {
        if (head == NULL) {
            return false;
        }
        
        ListNode *quicker = head->next;
        ListNode *slower = head;
        
        while ((quicker != NULL && quicker->next != NULL) && slower != NULL && quicker != slower) {
            quicker = quicker->next->next;
            slower = slower->next;
        }
        
        return quicker == slower;
    }
};

 

posted @ 2014-05-13 20:42  ThreeMonkey  阅读(80)  评论(0编辑  收藏  举报