python3 链表_python3实现链表
#鏈表節(jié)點結構實現(xiàn) 私有屬性_pro_item是指向下個節(jié)點的指針,_item為此節(jié)點的值
classNode():def __init__(self,item = None,pos_item=None):
self._item=item
self._next=pos_itemdef __repr__(self):'''用來定義Node的字符輸出,
print為輸出item'''
returnstr(self._item)#單鏈表實現(xiàn)
classChain():def __init__(self):
self._head=None
self.length=0#判空
defisEmpty(self):return self.length ==0#鏈表結尾插入
defappend(self,item):ifisinstance(item,Node):
node=itemelse:
node=Node(item)if self._head ==None:
self._head=nodeelse:
be_node=self._headwhilebe_node._next:
be_node=be_node._next
be_node._next=node
self.length+= 1
#插入數(shù)據(jù)
definsert(self,index,item):ifself.isEmpty():print('this chain table is empty')return
if index<0 or index >=self.length:print("error: out of index")returnin_node=Node(item)
node=self._head
count= 1
whileTrue:
node=node._next
count+= 1
if count ==index:
next_node=node._next
node._next=in_node
in_node._next=next_node
self.length+= 1
return
#node = s
#刪除數(shù)據(jù)
defdelete(self,index):ifself.isEmpty():print('this chain table is empty')return
if index<0 or index >=self.length:print("error: out of index")return
#if index == 0
#self._head = None
else:
node=self._head
count=0whileTrue:
count+= 1
if index ==count:
node._next=node._next._nextbreaknode=node._next
self.length-= 1
def __repr__(self):ifself.isEmpty():print("the chain table is empty")returnnlist= ""node=self._headwhilenode:
nlist+= node._item +''node=node._nextreturnnlistif __name__ == '__main__':
chain=Chain()
chain.append('A')
chain.append('B')
chain.append('C')
chain.append('D')
chain.append('E')
chain.append('F')
chain.append('G')
chain.insert(4,'p')
chain.delete(3)print(chain,chain._head._item,chain.length)
總結
以上是生活随笔為你收集整理的python3 链表_python3实现链表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3写一个计算器_Python
- 下一篇: 华为5720设置静态路由不通_如何设置静