Add Python codes for the chapter

of array and linked list.
This commit is contained in:
krahets
2022-11-25 03:59:38 +08:00
parent 9a861140d8
commit cbf4ab0aaa
8 changed files with 503 additions and 22 deletions

View File

@@ -77,7 +77,18 @@ comments: true
=== "Python"
```python title=""
""" 初始化链表 1 -> 3 -> 2 -> 5 -> 4 """
# 初始化各个结点
n0 = ListNode(1)
n1 = ListNode(3)
n2 = ListNode(2)
n3 = ListNode(5)
n4 = ListNode(4)
# 构建引用指向
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
```
## 链表优点
@@ -118,7 +129,20 @@ comments: true
=== "Python"
```python title=""
""" 在链表的结点 n0 之后插入结点 P """
def insert(n0, P):
n1 = n0.next
n0.next = P
P.next = n1
""" 删除链表的结点 n0 之后的首个结点 """
def remove(n0):
if not n0.next:
return
# n0 -> P -> n1
P = n0.next
n1 = P.next
n0.next = n1
```
## 链表缺点
@@ -148,7 +172,13 @@ comments: true
=== "Python"
```python title=""
""" 访问链表中索引为 index 的结点 """
def access(head, index):
for _ in range(index):
head = head.next
if not head:
return None
return head
```
**链表的内存占用多。** 链表以结点为单位,每个结点除了保存值外,还需额外保存指针(引用)。这意味着同样数据量下,链表比数组需要占用更多内存空间。
@@ -182,7 +212,15 @@ comments: true
=== "Python"
```python title=""
""" 在链表中查找值为 target 的首个结点 """
def find(head, target):
index = 0
while head:
if head.val == target:
return index
head = head.next
index += 1
return -1
```
## 常见链表类型
@@ -214,7 +252,12 @@ comments: true
=== "Python"
```python title=""
""" 双向链表结点类 """
class ListNode:
def __init__(self, x):
self.val = x # 结点值
self.next = None # 指向后继结点的指针(引用)
self.prev = None # 指向前驱结点的指针(引用)
```
![linkedlist_common_types](linked_list.assets/linkedlist_common_types.png)