查看链表是否有环
[题](判断链表中是否有环_牛客题霸_牛客网 (nowcoder.com))
代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23/**
* 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) {
ListNode* slow = head;
ListNode* fast = head;
while (fast != nullptr && fast->next != nullptr) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
return true;
}
}
return false;
}
};提示
- 使用快慢指针,如果快指针与慢指针重合,则说明有环
理解
-
问题
-
查看链表是否有环
https://tsy244.github.io/2023/05/01/算法/newcoder/查看链表是否有环/