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;
}
};
本文介绍了一种使用快慢指针的方法来判断链表中是否存在环。通过定义两个指针,一个每次移动一步,另一个每次移动两步,若两者相遇则说明链表中有环。这种方法无需额外空间。

被折叠的 条评论
为什么被折叠?



