python列表操作实例
本文实例讲述了python列表操作的方法。分享给大家供大家参考。
具体实现方法如下:
classNode:
"""Singlenodeinadatastructure"""
def__init__(self,data):
"""Nodeconstructor"""
self._data=data
self._nextNode=None
def__str__(self):
"""Nodedatarepresentation"""
returnstr(self._data)
classList:
"""Linkedlist"""
def__init__(self):
"""Listconstructor"""
self._firstNode=None
self._lastNode=None
def__str__(self):
"""Liststringrepresentation"""
ifself.isEmpty():
return"empty"
currentNode=self._firstNode
output=[]
whilecurrentNodeisnotNone:
output.append(str(currentNode._data))
currentNode=currentNode._nextNode
return"".join(output)
definsertAtFront(self,value):
"""Insertnodeatfrontoflist"""
newNode=Node(value)
ifself.isEmpty(): #Listisempty
self._firstNode=self._lastNode=newNode
else: #Listisnotempty
newNode._nextNode=self._firstNode
self._firstNode=newNode
definsertAtBack(self,value):
"""Insertnodeatbackoflist"""
newNode=Node(value)
ifself.isEmpty(): #Listisempty
self._firstNode=self._lastNode=newNode
else: #Listisnotempty
self._lastNode._nextNode=newNode
self._lastNode=newNode
defremoveFromFront(self):
"""Deletenodefromfrontoflist"""
ifself.isEmpty(): #raiseexceptiononemptylist
raiseIndexError,"removefromemptylist"
tempNode=self._firstNode
ifself._firstNodeisself._lastNode: #onenodeinlist
self._firstNode=self._lastNode=None
else:
self._firstNode=self._firstNode._nextNode
returntempNode
defremoveFromBack(self):
"""Deletenodefrombackoflist"""
ifself.isEmpty(): #raiseexceptiononemptylist
raiseIndexError,"removefromemptylist"
tempNode=self._lastNode
ifself._firstNodeisself._lastNode: #onenodeinlist
self._firstNode=self._lastNode=None
else:
currentNode=self._firstNode
#locatesecond-to-lastnode
whilecurrentNode._nextNodeisnotself._lastNode:
currentNode=currentNode._nextNode
currentNode._nextNode=None
self._lastNode=currentNode
returntempNode
defisEmpty(self):
"""ReturnstrueifListisempty"""
returnself._firstNodeisNone
希望本文所述对大家的Python程序设计有所帮助。
热门推荐
10 俄语祝福语贺卡文案简短
11 校长退休文案祝福语简短
12 结婚多层蛋糕祝福语简短
13 班级集体生日祝福语简短
14 经典送别祝福语大全简短
15 长辈生日祝福语简短女性
16 迎接朋友蛋糕祝福语简短
17 50多岁生日简短祝福语
18 提早庆祝生日祝福语简短