classNode():def__init__(self,item):
self.val = item
self.next=NoneclassSinglelink():def__init__(self,node=None):
self._head = node
defis_empty(self):return self._head ==Nonedeflength(self):
count =0
cur = self._head
while cur !=None:
count +=1
cur = cur.nextreturn count
# 遍历deftravel(self):
cur = self._head
while cur !=None:print(cur.val,end=' ')
cur = cur.next# 尾插defappend(self,item):if self.is_empty():
self._head = Node(item)else:
cur = self._head
while cur.next!=None:
cur = cur.next
cur.next= Node(item)# 头插defadd(self,item):
node = Node(item)
node.next= self._head
self._head = node
# 指定位置插入definsert(self,item,n):if n <=0:
self.add(item)elif n > self.length()-1:
self.append(item)else:
cur = self._head
while n >1:
cur = cur.next
n -=1
node = Node(item)
node.next= cur.next
cur.next= node
# 查找defsearch(self,item):
cur = self._head
while cur !=None:if cur.val == item:returnTrueelse:
cur = cur.nextreturnFalse# 删除defremove(self,item):
cur = self._head
pre =Nonewhile cur !=None:if cur.val == item:if cur == self._head:
self._head = cur.nextelse:
pre.next= cur.next
pre = cur
cur = cur.next
link = Singlelink()
link.append(3)
link.add(5)
link.add(8)
link.insert(4,2)
link.remove(8)print(link.search(1))print(link.travel())