本文章向大家介紹怎么在python中對鏈表進行反轉(zhuǎn),主要包括怎么在python中對鏈表進行反轉(zhuǎn)的使用實例、應用技巧、基本知識點總結(jié)和需要注意事項,具有一定的參考價值,需要的朋友可以參考一下。
Python主要應用于:1、Web開發(fā);2、數(shù)據(jù)科學研究;3、網(wǎng)絡爬蟲;4、嵌入式應用開發(fā);5、游戲開發(fā);6、桌面應用開發(fā)。
第一種方式:循壞迭代
循壞迭代算法需要三個臨時變量:pre、head、next,臨界條件是鏈表為None或者鏈表就只有一個節(jié)點。
# encoding: utf-8 class Node(object): def __init__(self): self.value = None self.next = None def __str__(self): return str(self.value) def reverse_loop(head): if not head or not head.next: return head pre = None while head: next = head.next # 緩存當前節(jié)點的向后指針,待下次迭代用 head.next = pre # 這一步是反轉(zhuǎn)的關(guān)鍵,相當于把當前的向前指針作為當前節(jié)點的向后指針 pre = head # 作為下次迭代時的(當前節(jié)點的)向前指針 head = next # 作為下次迭代時的(當前)節(jié)點 return pre # 返回頭指針,頭指針就是迭代到最后一次時的head變量(賦值給了pre)
測試一下:
if __name__ == '__main__': three = Node() three.value = 3 two = Node() two.value = 2 two.next = three one = Node() one.value = 1 one.next = two head = Node() head.value = 0 head.next = one newhead = reverse_loop(head) while newhead: print(newhead.value, ) newhead = newhead.next
輸出:
3 2 1 0 2
第二種方式:遞歸
遞歸的思想就是:
head.next = None head.next.next = head.next head.next.next.next = head.next.next ... ...
head的向后指針的向后指針轉(zhuǎn)換成head的向后指針,依此類推。
實現(xiàn)的關(guān)鍵步驟就是找到臨界點,何時退出遞歸。當head.next為None時,說明已經(jīng)是最后一個節(jié)點了,此時不再遞歸調(diào)用。
def reverse_recursion(head): if not head or not head.next: return head new_head = reverse_recursion(head.next) head.next.next = head head.next = None return new_head
到此這篇關(guān)于怎么在python中對鏈表進行反轉(zhuǎn)的文章就介紹到這了,更多相關(guān)的內(nèi)容請搜索創(chuàng)新互聯(lián)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持創(chuàng)新互聯(lián)!
網(wǎng)站標題:怎么在python中對鏈表進行反轉(zhuǎn)-創(chuàng)新互聯(lián)
轉(zhuǎn)載來于:http://www.chinadenli.net/article16/djsdgg.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供軟件開發(fā)、動態(tài)網(wǎng)站、網(wǎng)站制作、面包屑導航、ChatGPT、商城網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容