您的位置:首页 > 编程语言 > C语言/C++

LeetCode 141: Linked List Cycle

2016-06-22 10:28 267 查看

141. Linked List Cycle

Difficulty: Easy

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

Follow up:

Can you solve it without using extra space?

思路

定义两个指针,同时从链表头结点出发,一个指针一次走一步,另一个指针一次走两步。如果快的指针追上了慢的指针,存在环;如果快的指针追上之前就走到了链表末尾,不存在环。

代码

[C++]

class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL)
return false;
struct ListNode *slow = head->next;
if (slow == NULL)
return false;
struct ListNode *fast = slow->next;
while (fast != NULL && slow != NULL) {
if (fast == slow)
return true;
slow = slow->next;
fast = fast->next;
if (fast != NULL)
fast = fast->next;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表 C++