• 循序链表创建
  • 链表头结点插入
  • 链表尾节点插入
  • 链表头结点删除
  • 链表尾节点删除
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
80
"""
双向链表
Copyright ©conghaoyuan@gmail.comm
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None


class DoubleLinkedList:
def __init__(self):
self.head = None

def is_empty(self):
return self.head is None

def print_list(self):
cur = self.head
while cur is not None:
print(cur.data)
cur = cur.next

def insert(self, data):
node = Node(data)
if self.is_empty():
self.head = node
return

self.head.prev = node
node.next = self.head
self.head = node

def append(self, data):
node = Node(data)
if self.is_empty():
self.head = node

cur = self.head
while cur.next:
cur = cur.next

cur.next = node
node.prev = cur

def delete(self):
if self.is_empty():
return
self.head = self.head.next
self.head.prev = None

def remove(self):
if self.is_empty():
return
cur = self.head
while cur.next:
cur = cur.next

cur.prev.next = None
cur.prev = None


if __name__ == "__main__":
dl = DoubleLinkedList()
dl.insert(1)
dl.insert(2)
dl.insert(3)
dl.insert(4)
dl.insert(5)
dl.append(6)
dl.append(7)
dl.append(8)
dl.append(9)
dl.print_list()
print()

dl.delete()
dl.remove()
dl.print_list()