-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path141.环形链表.py
53 lines (39 loc) · 1.07 KB
/
141.环形链表.py
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
#
# @lc app=leetcode.cn id=141 lang=python3
#
# [141] 环形链表
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# # 使用O(n)的空间复杂度
# def hasCycle(self, head: ListNode) -> bool:
# if not head:
# return head
# tmp_list = []
# while head !=None:
# if head in tmp_list:
# return True
# tmp_list.append(head)
# head = head.next
# return False
def hasCycle(self, head: ListNode) -> bool:
if not head:
return head
slow = head
fast = head
while slow and fast:
slow = slow.next
if fast.next:
fast = fast.next.next
else:
return False
# is 表示内存中的地址是否相同
if fast is slow:
return True
return False
# @lc code=end