溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python單鏈表如何反轉(zhuǎn)

發(fā)布時間:2022-05-07 12:08:28 來源:億速云 閱讀:243 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“python單鏈表如何反轉(zhuǎn)”,在日常操作中,相信很多人在python單鏈表如何反轉(zhuǎn)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”python單鏈表如何反轉(zhuǎn)”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

代碼如下:

class Node(object):
    def __init__(self, elem, next_=None):
        self.elem = elem
        self.next = next_
 
def reverseList(head):
    if head == None or head.next==None:  # 若鏈表為空或者僅一個數(shù)就直接返回
        return head 
    pre = None
    next = None
    while(head != None): 
        next = head.next     # 1
        head.next = pre     # 2
        pre = head      # 3
        head = next      # 4
    return pre

if __name__ == '__main__':
    l1 = Node(3)    # 建立鏈表3->2->1->9->None
    l1.next = Node(2)
    l1.next.next = Node(1)
    l1.next.next.next = Node(9)
    l = reverseList(l1)
    print (l.elem, l.next.elem, l.next.next.elem, l.next.next.next.elem)

原始單鏈表:

python單鏈表如何反轉(zhuǎn)

反轉(zhuǎn)后單鏈表:

python單鏈表如何反轉(zhuǎn)

反轉(zhuǎn)過程如下:

python單鏈表如何反轉(zhuǎn)

第一步:next = head.next
將 head.next 賦值給 next 變量,即next 指向了節(jié)點2,先將節(jié)點2 保存起來。

第二步:head.next = pre (初始pre==None)
將 pre 變量賦值給 head.next,即 此時節(jié)點1 指向了 None

第三步:pre = head
將 head 賦值給了 pre,即 pre 指向節(jié)點1,將節(jié)點1 設(shè)為“上一個節(jié)點”

第四步:head = next
將 next 賦值給 head,即 head 指向了節(jié)點2,此時節(jié)點2 設(shè)為“頭節(jié)點”

第一次循環(huán)完畢,進入第二次循環(huán),如下圖:

python單鏈表如何反轉(zhuǎn)

第一步:next = head.next
將 head.next 賦值給 next 變量,即 next 指向了節(jié)點3,先將節(jié)點3 保存起來。

第二步:head.next = pre (此時的pre已經(jīng)不為None)
將 pre 賦值給 head.next,pre 在上一次循環(huán)的時候指向了節(jié)點1,那么這一步的意義就是節(jié)點2 指向了 節(jié)點1,完成1和2節(jié)點的反轉(zhuǎn)。

第三步:pre = head
將 head 賦值給了 pre,即 pre 指向節(jié)點2,將節(jié)點2 設(shè)為“上一個節(jié)點”

第四步:head = next
將 next 賦值給 head,即 head 指向了節(jié)點3。此時節(jié)點3 設(shè)為“頭節(jié)點”

第二次循環(huán)完畢,以此類推!第三次第四次第五次循環(huán)。最后反轉(zhuǎn)成如下圖

python單鏈表如何反轉(zhuǎn)

若干注意點:

(1)幫助記憶圖:

python單鏈表如何反轉(zhuǎn)

(2)當前頭節(jié)點的下一個節(jié)點一定要保存(比如:當前頭節(jié)點為2,先將節(jié)點3 保存起來)

(3)實現(xiàn)反轉(zhuǎn)的key point: head.next = pre

到此,關(guān)于“python單鏈表如何反轉(zhuǎn)”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI