-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode142.cpp
72 lines (67 loc) · 1.77 KB
/
leetcode142.cpp
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*************************************************
Author: wenhaofang
Date: 2023-03-12
Description: leetcode142 - Linked List Cycle II
*************************************************/
#include <bits/stdc++.h>
using namespace std;
/**
* 方法一:快慢指针
*
* 理论时间复杂度:O(n),其中 n 为链表长度
* 理论空间复杂度:O(1)
*/
/**
* 思路
*
* 慢指针每次走一步,快指针每次走两步
*
* 若链表有环,则二者相遇在环上某一点,若链表无环,则快指针会到达链表末尾
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
// 特判
if (!head) {
return nullptr;
}
// 快慢指针
ListNode* slow = head;
ListNode* fast = head;
while (fast -> next != nullptr && fast -> next -> next != nullptr) {
slow = slow -> next;
fast = fast -> next -> next;
if (slow == fast) {
// 找出环的起点
slow = head;
while (slow != fast) {
slow = slow -> next;
fast = fast -> next;
}
return slow;
}
}
return nullptr;
}
};
/**
* 测试
*/
int main() {
Solution* solution = new Solution();
ListNode* n4 = new ListNode(4);
ListNode* n3 = new ListNode(0);
ListNode* n2 = new ListNode(2);
ListNode* n1 = new ListNode(3);
n4 -> next = n2;
n3 -> next = n4;
n2 -> next = n3;
n1 -> next = n2;
ListNode* ans = solution -> detectCycle(n1);
cout << ans -> val << endl;
}