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

class SLinkedList:
def __init__(self) -> None:
self.head = None

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

def print_list(self):
lists = []
if self.is_empty():
return lists
cur = self.head
while cur:
lists.append(cur.data)
cur = cur.next
print(lists)

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

def append(self, data):
node = Node(data)
if self.is_empty():
self.head = node
return
cur = self.head
while cur.next:
cur = cur.next
cur.next = node


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

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

prev.next = None


if __name__ == '__main__':
sl = SLinkedList()
sl.append(1)
sl.append(2)
sl.append(3)
sl.append(4)
sl.append(5)
sl.print_list()

sl.insert(6)
sl.insert(7)
sl.insert(8)
sl.print_list()

sl.delete()
sl.remove()
sl.print_list()