您好,登錄后才能下訂單哦!
本文章向大家介紹利用python怎么對單鏈表進(jìn)行反轉(zhuǎn),主要包括利用python怎么對單鏈表進(jìn)行反轉(zhuǎn)的使用實(shí)例、應(yīng)用技巧、基本知識(shí)點(diǎn)總結(jié)和需要注意事項(xiàng),具有一定的參考價(jià)值,需要的朋友可以參考一下。
Python是一種編程語言,內(nèi)置了許多有效的工具,Python幾乎無所不能,該語言通俗易懂、容易入門、功能強(qiáng)大,在許多領(lǐng)域中都有廣泛的應(yīng)用,例如最熱門的大數(shù)據(jù)分析,人工智能,Web開發(fā)等。
1.循環(huán)反轉(zhuǎn)單鏈表
循環(huán)的方法中,使用pre指向前一個(gè)結(jié)點(diǎn),cur指向當(dāng)前結(jié)點(diǎn),每次把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
>>>
class ListNode: def __init__(self,x): self.val=x; self.next=None; def recurse(head,newhead): #遞歸,head為原鏈表的頭結(jié)點(diǎn),newhead為反轉(zhuǎn)后鏈表的頭結(jié)點(diǎn) 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;
到此這篇關(guān)于利用python怎么對單鏈表進(jìn)行反轉(zhuǎn)的文章就介紹到這了,更多相關(guān)的內(nèi)容請搜索億速云以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持億速云!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。