现在的位置: 首页 > 综合 > 正文

LeetCode | Linked List Cycle

2014年10月03日 ⁄ 综合 ⁄ 共 583字 ⁄ 字号 评论关闭

题目:

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;
        int count =10000;
        ListNode*slow=head;
        ListNode*fast=head;
        
        do
        {
            if(slow==NULL)
                return false;
            else
                slow=slow->next;
            if(fast->next==NULL||fast->next->next==NULL)
                return false;
            else
                fast=fast->next->next;
            if(slow==fast)
            {
                return true;
            }
            else
            {
                count--;
            }
            if(count==0)
                return false;
        }while(true);
    }
};

抱歉!评论已关闭.