码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ - Linked List Cycle

时间:2014-05-16 05:19:21      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   java   

题目:

  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

标签:style   blog   class   code   c   java   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!