Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fc5923d

Browse files
Merge pull request #44 from KongJHong/master
Add solution 142[CPP]
2 parents 47489a6 + c6e7ef5 commit fc5923d

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

‎solution/142.Linked List Cycle II/README.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,4 +67,32 @@ public class Solution {
6767

6868
}
6969
}
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+
7098
```
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /