您的位置:首页 > 其它

LeetCode:Linked List Cycle

2015-11-26 23:06 197 查看


Linked List Cycle

Total Accepted: 83564 Total
Submissions: 228287 Difficulty: Medium

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

Can you solve it without using extra space?

思路:

使用一个快指针fast和一个慢指针slow,快指针的速度是慢指针的2倍。

如果fast指针能追上慢指针slow,还代表有环存在。

因为两个指针的速度相差1,所以有环的话一定可以追上。

code:

/**
 * 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 *fast,*slow;
        fast=head;slow=head;
        while(slow && fast && fast->next) 
        {
            slow=slow->next;
            fast=fast->next->next;
            if(fast==slow) return true;
        }
        return false;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: