-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path142.hpp
55 lines (42 loc) · 1.13 KB
/
142.hpp
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
//
// Created by bai on 17-6-30.
//
#ifndef LEETCODE_142_HPP
#define LEETCODE_142_HPP
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <numeric>
#include "../common/leetcode.hpp"
using namespace std;
/**
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == nullptr || head->next == nullptr) {
return nullptr;
}
ListNode *slow = head, *faster = head, *entry = head;
while (faster->next != nullptr && faster->next->next != nullptr) {
slow = slow->next;
faster = faster->next->next;
if (slow == faster) {
while (entry != slow) {
slow = slow->next;
entry = entry->next;
}
return entry;
}
}
return nullptr;
}
};
#endif //LEETCODE_142_HPP