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