We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 42d78a0 commit 0146097Copy full SHA for 0146097
51. 环形链表.md
@@ -0,0 +1,26 @@
1
+***给你一个链表的头节点 head ,判断链表中是否有环。***
2
+
3
+
4
5
+```
6
+# Definition for singly-linked list.
7
+# class ListNode:
8
+# def __init__(self, x):
9
+# self.val = x
10
+# self.next = None
11
12
+class Solution:
13
+ def hasCycle(self, head: Optional[ListNode]) -> bool:
14
+ #我们定义两个指针,一快一满。慢指针每次只移动一步,而快指针每次移动两步。
15
+ #初始时,慢指针在位置 head,而快指针在位置 head.next。这样一来,如果在移动的过程中,快指针反过来追上慢指针,就说明该链表为环形链表。否则快指针将到达链表尾部,该链表不为环形链表。
16
+ if not head or not head.next:
17
+ return False
18
+ slow = head
19
+ fast = head.next
20
+ while slow != fast:
21
+ if not fast or not fast.next:
22
23
+ slow = slow.next
24
+ fast = fast.next.next
25
+ return True
26
images/algo26.jpg
9.22 KB
0 commit comments