Floyd 快慢指针,slow 走一步 fast 走两步,相遇则有环。
OJ: leetcodecn
题目 ID: linked-list-cycle
难度:入门
标签:链表双指针哈希表cpppython
日期: 2026-07-28 22:05
题意
判断链表是否有环。
思路
哈希集合记录已访问节点 O(n) 空间。Floyd 快慢指针 O(1) 空间:慢指针每次走一步,快指针每次走两步,若有环则必相遇。
代码
cpp
/**
* Author by Rainboy
*/
// main.cpp:Floyd 快慢指针,O(n) O(1)。
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
auto slow = head, fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
return false;
}
};
ListNode *build(istream &in, int n) {
if (!n)
return nullptr;
auto head = new ListNode(0), cur = head;
for (int i = 0, v; i < n; i++) {
in >> v;
cur->next = new ListNode(v);
cur = cur->next;
}
return head->next;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
auto head = build(cin, n);
cout << Solution().hasCycle(head) << '\n';
return 0;
}python
#!/usr/bin/env python3
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
def build(arr):
dummy = cur = ListNode(0)
for v in arr:
cur.next = ListNode(v)
cur = cur.next
return dummy.next
def main() -> None:
n = int(input())
a = list(map(int, input().split()))
head = build(a)
print(Solution().hasCycle(head))
if __name__ == "__main__":
main()复杂度
- 时间复杂度:O(n)。
- 空间复杂度:O(1)。
总结
Floyd 判环是快慢指针的经典应用。快指针每轮多走一步,在环内一定能追上慢指针。