File tree 2 files changed +50
-0
lines changed
solution/142.Linked List Cycle II
2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change @@ -67,4 +67,32 @@ public class Solution {
67
67
68
68
}
69
69
}
70
+ ```
71
+
72
+ #### CPP
73
+
74
+ ``` C++
75
+ class Solution {
76
+ public:
77
+ ListNode * detectCycle(ListNode * head) {
78
+ if(head == NULL)return NULL;
79
+ ListNode * fast = head;
80
+ ListNode * slow = head;
81
+ while(fast != NULL && fast->next != NULL){
82
+ fast = fast->next->next;
83
+ slow = slow->next;
84
+
85
+ if(fast == slow){
86
+ slow = head;
87
+ while(slow != fast){
88
+ fast = fast->next;
89
+ slow = slow->next;
90
+ }
91
+ return fast;
92
+ }
93
+ }
94
+ return NULL;//无环
95
+ }
96
+ };
97
+
70
98
```
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ ListNode *detectCycle (ListNode *head) {
4
+ if (head == NULL )return NULL ;
5
+ ListNode *fast = head;
6
+ ListNode *slow = head;
7
+ while (fast != NULL && fast->next != NULL ){
8
+ fast = fast->next ->next ;
9
+ slow = slow->next ;
10
+
11
+ if (fast == slow){
12
+ slow = head;
13
+ while (slow != fast){
14
+ fast = fast->next ;
15
+ slow = slow->next ;
16
+ }
17
+ return fast;
18
+ }
19
+ }
20
+ return NULL ;// 无环
21
+ }
22
+ };
You can’t perform that action at this time.
0 commit comments