最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python算法題 鏈表反轉(zhuǎn)詳解

 更新時(shí)間:2019年07月02日 08:54:47   作者:FOOFISH-PYTHON之禪  
這篇文章主要介紹了python算法題 鏈表反轉(zhuǎn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

鏈表的反轉(zhuǎn)是一個(gè)很常見(jiàn)、很基礎(chǔ)的數(shù)據(jù)結(jié)構(gòu)題,輸入一個(gè)單向鏈表,輸出逆序反轉(zhuǎn)后的鏈表,如圖:上面的鏈表轉(zhuǎn)換成下面的鏈表。實(shí)現(xiàn)鏈表反轉(zhuǎn)有兩種方式,一種是循環(huán)迭代,另外一種方式是遞歸。

第一種方式:循壞迭代

循壞迭代算法需要三個(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的向后指針,依此類(lèi)推。

實(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


以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

刚察县| 如东县| 沁阳市| 罗江县| 嘉定区| 穆棱市| 通许县| 鹿邑县| 保山市| 六枝特区| 花莲市| 抚松县| 晋州市| 怀仁县| 南涧| 淮北市| 兴山县| 新巴尔虎左旗| 河西区| 大名县| 蒲城县| 璧山县| 民乐县| 乐昌市| 抚顺市| 安塞县| 启东市| 民勤县| 松江区| 都江堰市| 中方县| 金秀| 黎川县| 景谷| 五常市| 谢通门县| 新兴县| 元江| 佳木斯市| 株洲县| 龙里县|