Skip to content

Commit 221dba5

Browse files
Add files via upload
1 parent 75fdeb3 commit 221dba5

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// 双指针 一个快指针,一个慢指针
2+
// Runtime: 12 ms, faster than 26.05% of C++ online submissions for Linked List Cycle.
3+
// Memory Usage: 6.7 MB, less than 0.69% of C++ online submissions for Linked List Cycle.
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+
bool hasCycle(ListNode *head)
17+
{
18+
if (head == 0)
19+
return false;
20+
21+
ListNode *fastPtr = head->next, *slowPtr = head;
22+
23+
while (slowPtr != fastPtr)
24+
{
25+
if (slowPtr->next != 0 && fastPtr->next != 0 && fastPtr->next->next !=0)
26+
{
27+
// 慢指针每次一共一格,快指针每次移动两格
28+
slowPtr = slowPtr->next;
29+
fastPtr = fastPtr->next->next;
30+
}
31+
else
32+
return false;
33+
}
34+
return true;
35+
}
36+
};
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Runtime: 68 ms, faster than 18.16% of Python online submissions for Linked List Cycle.
2+
# Memory Usage: 16.2 MB, less than 89.08% of Python online submissions for Linked List Cycle.
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 hasCycle(self, head):
12+
"""
13+
:type head: ListNode
14+
:rtype: bool
15+
"""
16+
if head is None:
17+
return False
18+
fastPtr = head.next
19+
slowPtr = head
20+
21+
while fastPtr != slowPtr:
22+
if slowPtr.next is not None and fastPtr.next is not None and fastPtr.next.next is not None:
23+
slowPtr = slowPtr.next
24+
fastPtr = fastPtr.next.next
25+
else:
26+
return False
27+
return True

0 commit comments

Comments
 (0)