單鏈表反轉(zhuǎn)python實現(xiàn)代碼示例
單鏈表的反轉(zhuǎn)可以使用循環(huán),也可以使用遞歸的方式
1.循環(huán)反轉(zhuǎn)單鏈表
循環(huán)的方法中,使用pre指向前一個結(jié)點,cur指向當(dāng)前結(jié)點,每次把cur->next指向pre即可。
代碼:
class ListNode: def __init__(self,x): self.val=x; self.next=None; def nonrecurse(head): #循環(huán)的方法反轉(zhuǎn)鏈表 if head is None or head.next is None: return head; pre=None; cur=head; h=head; while cur: h=cur; tmp=cur.next; cur.next=pre; pre=cur; cur=tmp; return h; head=ListNode(1); #測試代碼 p1=ListNode(2); #建立鏈表1->2->3->4->None; p2=ListNode(3); p3=ListNode(4); head.next=p1; p1.next=p2; p2.next=p3; p=nonrecurse(head); #輸出鏈表 4->3->2->1->None while p: print p.val; p=p.next;
結(jié)果:
4
3
2
1
>>>
2.遞歸實現(xiàn)單鏈表反轉(zhuǎn)
class ListNode: def __init__(self,x): self.val=x; self.next=None; def recurse(head,newhead): #遞歸,head為原鏈表的頭結(jié)點,newhead為反轉(zhuǎn)后鏈表的頭結(jié)點 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; head=ListNode(1); #測試代碼 p1=ListNode(2); # 建立鏈表1->2->3->4->None p2=ListNode(3); p3=ListNode(4); head.next=p1; p1.next=p2; p2.next=p3; newhead=None; p=recurse(head,newhead); #輸出鏈表4->3->2->1->None while p: print p.val; p=p.next;
運行結(jié)果同上。
總結(jié)
以上就是本文關(guān)于單鏈表反轉(zhuǎn)python實現(xiàn)代碼示例的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關(guān)文章
pandas學(xué)習(xí)之df.set_index的具體使用
本文主要介紹了pandas學(xué)習(xí)之df.set_index的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08Python使用Pickle庫實現(xiàn)讀寫序列操作示例
這篇文章主要介紹了Python使用Pickle庫實現(xiàn)讀寫序列操作,結(jié)合實例形式分析了pickle模塊的功能、常用函數(shù)以及序列化與反序列化相關(guān)操作技巧,需要的朋友可以參考下2018-06-06python使用XPath解析數(shù)據(jù)爬取起點小說網(wǎng)數(shù)據(jù)
這篇文章主要介紹了python使用XPath解析數(shù)據(jù)爬取起點小說網(wǎng)數(shù)據(jù),幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-04-04