1. 程式人生 > >單鏈表的反轉 python實現例項

單鏈表的反轉 python實現例項

單鏈表反轉實現

1、遞迴實現

  根據遞迴,遞迴到最後一個節點(條件為head3為非空,其下一個指向為空),將其next指向前一個結點,前一個結點的指向為None。

 

 

 

def recurse(head, newhead):  # 遞迴,head為原連結串列的頭結點,newhead為反轉後連結串列的頭結點
        if head is None:
            return
        if head.next is None:
            newhead = head
        
else: newhead = recurse(head.next, newhead) head.next.next = head head.next = None return newhead

註釋:原來連結串列為{1,2,3,4}

head指向為1,pHead1=head.next   pHead2=pHead1.next    pHead3=pHead2.next

a、遞迴最後實現newhead=phead3

b、回到上次遞迴的結束下方

2、迴圈實現

    def ReverseList(self, pHead):
        if pHead is None or pHead.next is None:
            return pHead
        pre = None
        cur = pHead
        h = pHead
        while cur:
            h = cur
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur 
= tmp return h