File tree Expand file tree Collapse file tree 2 files changed +80
-0
lines changed Expand file tree Collapse file tree 2 files changed +80
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 双指针
2
+ // Runtime: 12 ms, faster than 29.54% of C++ online submissions for Linked List Cycle II.
3
+ // Memory Usage: 6.7 MB, less than 0.89% of C++ online submissions for Linked List Cycle II.
4
+
5
+ /* *
6
+ * Definition for singly-linked list.
7
+ * struct ListNode {
8
+ * int val;
9
+ * ListNode *next;
10
+ * ListNode(int x) : val(x), next(NULL) {}
11
+ * };
12
+ */
13
+ class Solution
14
+ {
15
+ public:
16
+ ListNode *detectCycle (ListNode *head)
17
+ {
18
+ if (head == 0 )
19
+ return 0 ;
20
+
21
+ ListNode *fastPtr = head, *slowPtr = head;
22
+
23
+ bool hasCycle = false ;
24
+ while (slowPtr->next != 0 && fastPtr->next != 0 && fastPtr->next ->next !=0 )
25
+ {
26
+ // 慢指针每次一共一格,快指针每次移动两格
27
+ slowPtr = slowPtr->next ;
28
+ fastPtr = fastPtr->next ->next ;
29
+ if (fastPtr == slowPtr)
30
+ {
31
+ hasCycle = true ;
32
+ break ;
33
+ }
34
+ }
35
+
36
+ if (hasCycle == false )
37
+ return 0 ;
38
+
39
+ // 此时链表中存在环
40
+ fastPtr = head;
41
+ while (slowPtr != fastPtr)
42
+ {
43
+ slowPtr = slowPtr->next ;
44
+ fastPtr = fastPtr->next ;
45
+ }
46
+ return fastPtr;
47
+ }
48
+ };
Original file line number Diff line number Diff line change
1
+ # Runtime: 44 ms, faster than 99.63% of Python online submissions for Linked List Cycle II.
2
+ # Memory Usage: 16.2 MB, less than 94.55% of Python online submissions for Linked List Cycle II.
3
+
4
+ # Definition for singly-linked list.
5
+ # class ListNode(object):
6
+ # def __init__(self, x):
7
+ # self.val = x
8
+ # self.next = None
9
+
10
+ class Solution (object ):
11
+ def detectCycle (self , head ):
12
+ """
13
+ :type head: ListNode
14
+ :rtype: ListNode
15
+ """
16
+ if head is None :
17
+ return None
18
+ fastPtr , slowPtr = head , head
19
+ hasCycle = False
20
+ while (slowPtr .next is not None and fastPtr .next is not None and fastPtr .next .next is not None ):
21
+ slowPtr = slowPtr .next
22
+ fastPtr = fastPtr .next .next
23
+ if slowPtr == fastPtr :
24
+ hasCycle = True
25
+ break
26
+ if not hasCycle :
27
+ return None
28
+ fastPtr = head
29
+ while fastPtr != slowPtr :
30
+ slowPtr = slowPtr .next
31
+ fastPtr = fastPtr .next
32
+ return fastPtr
You can’t perform that action at this time.
0 commit comments