<数据结构/算法> leetcode hot100系列. 141(142). 环形链表

[LeetCode hot 100] 141(142). 环形链表

题目链接

环形链表的判断在要求空间复杂度为O(1)时,需要使用Floyd判圈法来判断是否存在环。Floyd判圈法的具体讲解看这里

具体步骤为:

  1. 快指针fast和慢指针slow指向链表头(首元结点)
  2. fast每次移动两步,slow每次移动一步
  3. 如果遇到null说明没有环,如果fast和slow相遇说明有环,进入4
  4. 其中一个指针移回链表头,另一个不动
  5. 两个指针每次移动一步,直到相遇,就是环的入口

完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next && fast->next->next){
fast = fast->next->next;
slow = slow->next;
if(slow == fast){
fast = head;
while(fast != slow){
fast = fast->next;
slow = slow->next;
}
return fast;
}
}
return nullptr;
}
};

<数据结构/算法> leetcode hot100系列. 141(142). 环形链表
http://example.com/2024/08/21/lc_141_环形链表/
Author
dingzr2001
Posted on
August 21, 2024
Licensed under