Skip to content

Commit 0146097

Browse files
committed
update
1 parent 42d78a0 commit 0146097

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

51. 环形链表.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
***给你一个链表的头节点 head ,判断链表中是否有环。***
2+
3+
![algo26](./images/algo26.jpg)
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+
return False
23+
slow = slow.next
24+
fast = fast.next.next
25+
return True
26+
```

images/algo26.jpg

9.22 KB
Loading

0 commit comments

Comments
 (0)