链表的构成
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3b9b4b880764dfac165a250ec3a0142a.png)
头部添加元素
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6af4d19107549e76cbb0bc2fbb825bb3.png)
class SingleNode:
"""单链表的节点"""
def __init__(self, val):
self.val = val
self.next = None
class SingleLinkList(object):
"""单向链表"""
def __init__(self):
"""单向列表的初始化方法"""
self.__head = None
def add(self, val):
"""在链表头部添加元素"""
node = SingleNode(val)
node.next = self.__head
self.__head = node
def is_empty(self):
"""判断列表是否为空"""
return self.__head == None
def length(self):
cur = self.__head
count = 0
while cur != None:
count += 1
cur = cur.next
return count
def travel(self):
cur = self.__head
while cur != None:
val = cur.val
print(val)
cur = cur.next
print('')
def append(self, val):
"""尾部添加元素"""
node = SingleNode(val)
if self.is_empty():
self.__head = node
else:
cur = self.__head
while cur.next != None:
cur = cur.next
cur.next = node
def insert(self, index, val):
"""指定位置插入元素"""
if index <= 0:
self.add(val)
elif index > self.length() - 1:
self.append(val)
else:
node = SingleNode(val)
pre = self.__head
count = 0
while count < (index - 1):
count += 1
pre = pre.next
node.next = pre.next
pre.next = node
def remove(self, val):
"""删除指定节点"""
cur = self.__head
pre = None
while cur.val != val:
if cur.next == None:
print("没有这个元素")
break
else:
pre = cur
cur = cur.next
if not pre:
self.__head = cur.next
else:
pre.next = cur.next
def find_by_value(self, value):
cur = self.__head
while (cur is not None) and (cur.val != value):
cur = cur.next
return cur
if __name__ == '__main__':
ll = SingleLinkList()
ll.add(2)
ll.add(1)
ll.append(3)
ll.insert(1, 9)
ll.travel()
ll.remove(9)
ll.travel()
a = ll.find_by_value(1)
print(a.val)
ll.is_empty()