反轉單鏈表

2021-09-19 12:19:35 字數 1675 閱讀 1720

反轉鍊錶就是只通過改變指標的指向不開闢新的記憶體空間來把鍊錶反轉。

目錄

一、初始化:

二、開始反轉

三、**實現

cur為第乙個結點時,反轉後它將會成為最後乙個結點,所以它的next要指向none。cur指向第乙個結點,pre指向為none。

利用臨時變數temp儲存後面的鍊錶,因為沒有cur.next的指標引用會導致斷鏈,防止斷鏈用tamp儲存沒處理元素鍊錶的頭結點。

讓cur的next指標指向pre。

pre指向cur指向的結點

cur指向temp指向的位置

self.root = node(value) # 指頭結點

self.length = 0

self.tail = none

def reverse_l(self):

per = none # 指向當前結點的前驅結點

cur = self.root # 指向當前結點

while cur is not none:

if cur.next is none: # 最後乙個元素

self.root.next = cur # 把頭結點的next指向最後乙個結點

temp = cur.next # temp用於儲存當前元素後乙個元素的指標,防止斷鏈

cur.next = per

per = cur

cur = temp

傳頭指標的版本,只要改動一丟丟

def reverselist(self, phead):

# write code here

cur = phead

pre = none

while cur is not none:

if cur.next is none:

cur.next = pre

return cur

temp = cur.next

cur.next = pre

pre = cur

cur = temp

return phead

單鏈表反轉

單鏈表反轉,可以用迴圈做,當然也可以遞迴 詳見 include includestruct node 3 1 4 6 2 1 1 3 4 6 2 2 4 1 3 6 2 3 6 4 1 3 2 4 2 6 4 1 3 5 迴圈反轉,即依次改動3個指標值,直到鍊錶反轉完成 比如,上面第 1 行到第 2...

反轉單鏈表

include stdafx.h include include using namespace std struct listnode typedef listnode plistnode typedef plistnode list list creatlist return head void...

單鏈表反轉

想起很早以前某次面試,面試官很嚴肅的要求我現場手寫單鏈表反轉的 哥虎軀一震,心想 不就需要要個臨時變數來記錄位址嗎,用得著這樣煞有介事?雖然在那之前我的確沒寫過這個程式,哈哈哈 當時我草草寫了十來行 面試官不等我完成,就直接拿過去開始問問題。不知道是不是因為抗壓能力不足,在面試官的不斷 盤問 下,哥...