"""定义节点"""
classNode():def __init__(self, item):
self.item=item
self.next=None"""定义单向链表"""
classSingleList():"""将头指针设为链表的私有属性"""
def __init__(self, node=None):
self.__head =node"""判断是否为空"""
defis_Empty(self):return self.__head ==None"""链表长度,通过遍历获得
需要考虑特殊情况:链表为空时是否能够正确执行"""
defget_length(self):
cur= self.__headcount=0while cur !=None:
count+= 1cur=cur.nextreturncountdeftraver(self):
cur= self.__head
while cur !=None:print(cur.item, end=" ")
cur=cur.nextprint()"""头部添加元素
需要考虑特殊情况:链表为空时是否能够正确执行"""
defaddFirst(self, item):
node=Node(item)
node.next= self.__headself.__head =node"""尾部添加元素,首先需要遍历找到最后一个元素
需要考虑特殊情况:链表为空时是否能够正确执行"""
defaddLast(self, item):
node=Node(item)
cur= self.__head
if cur ==None:
self.__head =nodeelse:while cur.next !=None:
cur=cur.next
cur.next=node"""在指定位置添加元素,先找到添加的位置
需要考虑特殊情况:在头部和尾部以及为空时能否正确执行"""
definsert(self, index, item):if index <=0:
self.addFirst(item)elif index >=self.get_length():
self.addLast(item)else:
node=Node(item)
cur= self.__headcount= 1
while count
cur=cur.next
count+= 1node.next=cur.next
cur.next=node"""查找元素
注意链表为空的特殊情况"""
deffind(self, item):ifself.is_Empty():print("链表为空,无法查找")returncur= self.__headi=0while cur.next != None and not cur.item ==item:
cur=cur.next
i+= 1
if cur.item ==item:return("找到了,元素%s在%d处" %(item, i))else:return("没找到")"""删除指定位置元素"""
defremove(self, index):ifself.is_Empty():print("链表为空,无法删除")return
if index < 0 or index >self.get_length():print("索引越界,请检查!")returncur= self.__headpre=None
count=0if index ==0:
self.__head =cur.nextreturn
else:while count !=index:
pre=cur
cur=pre.next
count+= 1pre.next=cur.nextreturn
if __name__ == "__main__":
sl=SingleList()print(sl.is_Empty())
sl.find(7)
sl.insert(0,9)
sl.traver()
sl.addFirst(1)
sl.traver()
sl.addLast(2)
sl.addLast(3)
sl.addLast(4)
sl.addLast(5)
sl.addLast(6)
sl.traver()
sl.insert(-2, 21)
sl.traver()
sl.insert(20, 25)
sl.traver()
sl.insert(0,15)
sl.traver()
sl.insert(2, 17)
sl.traver()print(sl.find(7))print(sl.find(6))
sl.remove(3)
sl.traver()
sl.remove(0)
sl.traver()
sl.remove(-1)
sl.traver()
sl.remove(20)
sl.traver()