Skip to content

Commit 014d22b

Browse files
committed
Create Linked_List_Cycle_II.cc
1 parent f6719eb commit 014d22b

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Linked_List_Cycle_II.cc

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
ListNode *detectCycle(ListNode *head) {
12+
// IMPORTANT: Please reset any member data you declared, as
13+
// the same Solution instance will be reused for each test case.
14+
ListNode *fast = head, *slow = head;
15+
while (fast && fast->next) {
16+
fast = fast->next->next;
17+
slow = slow->next;
18+
if (fast == slow) {
19+
fast = head;
20+
while (fast != slow) {
21+
fast = fast->next;
22+
slow = slow->next;
23+
}
24+
return fast;
25+
}
26+
}
27+
return NULL;
28+
}
29+
};

0 commit comments

Comments
 (0)