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程序设计有所帮助。