輸入乙個鍊錶,反轉鍊錶後,輸出新鍊錶的表頭。
非常基礎的鍊錶題,幾乎所有學習鍊錶的程式設計師都會在一開始學習這個演算法。
唯一需要注意的是,當while迴圈結束時(也即是curnode到達了鍊錶尾),此時curnode.next並沒有被指向lastnode,需要在後面加上。
class
solution
:# 返回listnode
defreverselist
(self, phead)
:# write code here
if phead ==
none
or phead.
next
==none
:return phead
curnode = phead
lastnode =
none
nextnode = phead.
next
while curnode.
next
: curnode.
next
= lastnode
lastnode = curnode
curnode = nextnode
nextnode = curnode.
next
curnode.
next
= lastnode
return curnode
劍指offer JZ15反轉鍊錶
時間限制 c c 1秒,其他語言2秒 空間限制 c c 32m,其他語言64m 熱度指數 824838 本題知識點 鍊錶 輸入乙個鍊錶,反轉鍊錶後,輸出新鍊錶的表頭。function listnode x function reverselist phead let head phead let n...
劍指offer JZ15 反轉鍊錶
輸入乙個鍊錶,反轉鍊錶後,輸出新鍊錶的表頭。思路 1.利用乙個棧,注意反轉後的最後乙個元素需要把它的next置為空,否則會無限迴圈 struct listnode class solution listnode p phead listnode temp null while note.empty ...
劍指offer JZ15反轉鍊錶
題目描述 輸入乙個鍊錶,反轉鍊錶後,輸出新鍊錶的表頭。演算法思想 因為是將鍊錶進行反轉,因此主要的方法是先定義乙個頭結點,然後將不斷新建節點,將原鍊錶節點從前往後依次遍歷,取出每乙個節點的值,然後依次斷開新建節點與後面節點的連線,並將後面的鍊錶的頭結點儲存在乙個臨時變數中,這時將從原煉表中取出的節點...