鏈表的實現、輸出和反向 python


  鏈表節點包含兩個元素:節點的值和指向的下一個節點,因此可以定義鏈表的類為:

class linknode: def __init__(self,value=None,next=None): self.value=value self.next=next

  給定一個列表l,用此列表生成一個鏈表時,只需按順序遍歷列表,使用遍歷到的值生成鏈表節點,並在前后兩個節點之間建立聯系,最后返回頭節點。

def createlink(l): head=linknode(l[0]) nn=head for i in l[1:]: nn.next=linknode(i) nn=nn.next return head

  輸出一個鏈表,按順序訪問列表節點即可。

def printlist(head): if head==None: return node=head while node!=None: print(node.value) node=node.next

  鏈表的反向是指對鏈表的方向進行反轉。如給定鏈表:1->2->3->4->5,

反向后的鏈表為:5->4->3->2->1

反向的關鍵在於,在反向的過程中,不能丟掉了原來鏈表節點之間的聯系,如對前兩個節點反向時,執行2.next=1后,則對於前兩個節點,方向為2->1

但對於整個鏈表來說,由於2.next已經被更新,鏈表成為

就無法繼續訪問后續節點。所以,在反向的過程中,要記錄的節點有三個:前一個節點pre,當前節點cur,下一個節點next,這樣,在執行cur.next=pre后,還可以繼續對next進行操作,代碼如下。

def reverselink(head): if head==None: return
    if head.next==None: return head reversehead=None pre,cur,next=None,head,head.next while next!=None: cur.next=pre pre=cur cur=next next=next.next else:reversehead=cur return reversehead

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM