首页 > 其他 > 详细

LeetCode OJ - Linked List Cycle

时间:2014-05-16 05:17:37      阅读:371      评论:0      收藏:0      [点我收藏+]

题目:

  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

LeetCode OJ - Linked List Cycle

原文:http://www.cnblogs.com/dongguangqing/p/3726422.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!