-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathlinked_list_cycle.cpp
92 lines (79 loc) · 1.91 KB
/
linked_list_cycle.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* @Author: Chacha
* @Date: 2019-01-14 15:24:40
* @Last Modified by: Chacha
* @Last Modified time: 2021-03-26 17:35:37
*/
#include <iostream>
#include <string>
using namespace std;
/**
* Definition for singly-linked list(单向链表)
* Source: https://zh.wikipedia.org/wiki/链表
*/
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
/**
* Given a linked list, determine if it has a cycle in it.
* Example:
* Given -21->10->4->5, tail connects to node index 1, return true
* Source: https://leetcode.com/problems/linked-list-cycle/
*/
bool hasCycle(ListNode *head)
{
if (head == NULL || head->next == NULL)
return false;
ListNode *slow = head;
ListNode *fast = head->next;
while (fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
if (slow == fast)
return true;
}
return false;
}
/**
* Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
*
* Example:
* Given -21->10->4->5, tail connects to node index 1,return node 10
*
* Source:
*/
ListNode *detectCycle(ListNode *head)
{
if (head == NULL || head->next == NULL)
return NULL;
ListNode *slow = head;
ListNode *fast = head;
while (fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
if (slow == fast)
{
fast = head;
while (slow != fast)
{
fast = fast->next;
slow = slow->next;
}
return slow;
};
}
return NULL;
}
};
int main()
{
return 0;
}