LeetCode OJ - Linked List Cycle

时间:2014-05-16 05:19:21   收藏:0   阅读:271

题目:

  Given a linked list, determine if it has a cycle in it.

  Follow up:
    Can you solve it without using extra space?

解题思路:

  使用快慢指针,快指针每次走两步,慢指针每次走一步,若快指针能追上慢指针,则表明有圈。

代码如下:

bubuko.com,布布扣
/**
 * 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;
    }
};
bubuko.com,布布扣

 

LeetCode OJ - Linked List Cycle,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!