-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinked_List_Cycle_II.cpp
More file actions
57 lines (47 loc) · 1.1 KB
/
Linked_List_Cycle_II.cpp
File metadata and controls
57 lines (47 loc) · 1.1 KB
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
// Source : https://oj.leetcode.com/problems/linked-list-cycle-ii/
// Author : zheng yi xiong
// Date : 2014-12-03
/**********************************************************************************
*
* Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
* Follow up:
* Can you solve it without using extra space?
*
**********************************************************************************/
#include "stdafx.h"
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class CLinked_List_Cycle_II {
public:
ListNode *detectCycle(ListNode *head) {
if (NULL == head)
{
return NULL;
}
ListNode *pNode1 = head;
ListNode *pNode2 = head;
do
{
pNode1 = pNode1->next;
if (NULL == pNode2->next)
{
return NULL;
}
pNode2 = pNode2->next->next;
if (pNode1 == pNode2)
{
pNode2 = head;
while (pNode1 != pNode2)
{
pNode1 = pNode1->next;
pNode2 = pNode2->next;
}
return pNode1;
}
} while (NULL != pNode2);
return NULL;
}
};