python实现单链表

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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
class Node(object):
"""结点"""
def __init__(self, elem):
self.elem = elem
self.next = None


class SingleLinkList(object):
"""单链表"""
def __init__(self, Node = None):
self.__head = Node

def is_empty(self):
return self.__head == None

def length(self):
cur = self.__head
cnt = 0
while cur != None:
cnt += 1
cur = cur.next
return cnt

def travel(self):
cur = self.__head
while cur != None:
print(cur.elem, end=' ')
cur = cur.next

def add(self, item):
"""插入头结点"""
node = Node(item)
node.next = self.__head
self.__head = node

def append(self, item):
"""插入尾节点"""
node = Node(item)
if self.is_empty():
self.__head=node
else:
cur = self.__head

while cur.next != None:
cur = cur.next
cur.next = node

def insert(self, pose, item):
"""在指定位置插入结点"""
if pose<=0:
self.add(item)
elif pose >= self.length():
self.append(item)
else:
node = Node(item)
cnt = 0
cur = self.__head
pre = None
while cnt != pose:
pre = cur
cur = cur.next
cnt += 1
cur = node
cur.next = pre.next
pre.next = cur

def remove(self, item):
if self.is_empty():
print("链表为空,删除操作错误!")
else:
cur = self.__head
pre = None
if cur.elem == item:
self.__head = cur.next
del cur
return
while cur.elem != item:
pre = cur
cur = cur.next
if cur is None:
print("当前链表未找到要删除的元素!")
return
pre.next = cur.next
print("删除成功!")
del cur

def search(self, item):
cur = self.__head
pos = 1
while cur.elem != item:
cur = cur.next
pos +=1
if cur is None:
print("当前链表查无此元素!")
return
print(f"查找成功,该元素在链表中的第{pos}个位置")

if __name__ == "__main__":
slinklist = SingleLinkList()
slinklist.add('abc') # 链表头部添加元素
slinklist.add('小明')
slinklist.append(1) # 链表尾部添加元素
slinklist.append(100)
slinklist.remove("abcd") # 移除链表中的元素
slinklist.search(1) # 在链表中查找某个元素
slinklist.insert(5, "hello world")
print(f"当前链表长度为{slinklist.length()}")
slinklist.travel() # 遍历链表中的元素并打印
print(slinklist.is_empty())