链表
什么是链表
链表(Linked list)是一种常见的基础数据结构,是一种线性表,但是并不会按线性的顺序存储数据,而是在每一个节点里存到下一个节点的指针(Pointer)。由于不必须按顺序存储,链表在插入的时候可以达到O(1)的复杂度,比另一种线性表顺序表快得多,但是查找一个节点或者访问特定编号的节点则需要O(n)的时间,而顺序表相应的时间复杂度分别是O(logn)和O(1)。
特点
使用链表结构可以克服数组链表需要预先知道数据大小的缺点,链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理。但是链表失去了数组随机读取的优点,同时链表由于增加了结点的指针域,空间开销比较大。
操作
- init():初始化
- insert(): 插入
- trave(): 遍历
- delete(): 删除
- find(): 查找
实现
此处仅实现双向列表
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
class
LinkedList
(
)
:
def
__init__
(
self
,
value
=
None
)
:
self
.
value
=
value
# 前驱
self
.
before
=
None
# 后继
self
.
behind
=
None
def
__str__
(
self
)
:
if
self
.
value
is
not
None
:
return
str
(
self
.
value
)
else
:
return
'None'
def
init
(
)
:
return
LinkedList
(
'HEAD'
)
def
delete
(
linked_list
)
:
if
isinstance
(
linked_list
,
LinkedList
)
:
if
linked_list
.
behind
is
not
None
:
delete
(
linked_list
.
behind
)
linked_list
.
behind
=
None
linked_list
.
before
=
None
linked_list
.
value
=
None
def
insert
(
linked_list
,
index
,
node
)
:
node
=
LinkedList
(
node
)
if
isinstance
(
linked_list
,
LinkedList
)
:
i
=
0
while
linked_list
.
behind
is
not
None
:
if
i
==
index
:
break
i
+=
1
linked_list
=
linked_list
.
behind
if
linked_list
.
behind
is
not
None
:
node
.
behind
=
linked_list
.
behind
linked_list
.
behind
.
before
=
node
node
.
before
,
linked_list
.
behind
=
linked_list
,
node
def
remove
(
linked_list
,
index
)
:
if
isinstance
(
linked_list
,
LinkedList
)
:
i
=
0
while
linked_list
.
behind
is
not
None
:
if
i
==
index
:
break
i
+=
1
linked_list
=
linked_list
.
behind
if
linked_list
.
behind
is
not
None
:
linked_list
.
behind
.
before
=
linked_list
.
before
if
linked_list
.
before
is
not
None
:
linked_list
.
before
.
behind
=
linked_list
.
behind
linked_list
.
behind
=
None
linked_list
.
before
=
None
linked_list
.
value
=
None
def
trave
(
linked_list
)
:
if
isinstance
(
linked_list
,
LinkedList
)
:
print
(
linked_list
)
if
linked_list
.
behind
is
not
None
:
trave
(
linked_list
.
behind
)
def
find
(
linked_list
,
index
)
:
if
isinstance
(
linked_list
,
LinkedList
)
:
i
=
0
while
linked_list
.
behind
is
not
None
:
if
i
==
index
:
return
linked
_list
i
+=
1
linked_list
=
linked_list
.
behind
else
:
if
i
<
index
:
raise
Exception
(
404
)
return
linked_list
|