劍指offer 15反轉鍊錶(Python)

2021-10-03 02:30:27 字數 1018 閱讀 1668

【題目】輸入乙個鍊錶,反轉鍊錶後,輸出新鍊錶的表頭。

【思路】現在有乙個鍊錶,我們需要將其反轉,需要的操作就是將現在的頭換成尾,尾部的指標指向空,然後從第二個開始,迴圈將next指向前乙個,此時,後面的未反轉的鍊錶沒法通過前乙個node指向了,所以需要有乙個指標指向後面還未反轉的鍊錶的頭部。

【**實現】

class

solution

:# 返回listnode

defreverselist

(self, phead)

:#首先考慮邊界條件

if phead ==

none

:return

none

if phead.

next

==none

:return phead

leftpointer = phead

midpointer = phead.

next

rightpointer = phead.

next

.next

leftpointer.

next

=none

# 頭換成尾,指向空

#後面未轉換的鍊錶為空則推出迴圈

while rightpointer !=

none

:#第二個指向前乙個

midpointer.

next

= leftpointer

#三個指標往後移一位

leftpointer = midpointer

midpointer = rightpointer

rightpointer = rightpointer.

next

#未反轉的鍊錶為空,此時midpointer就是最後乙個節點,將其指向前面乙個節點,就完成了整個鍊錶的反轉

midpointer.

next

= leftpointer

return midpointer

劍指offer 15 反轉鍊錶

輸入乙個鍊錶,反轉鍊錶後,輸出鍊錶的所有元素。反轉鍊錶只需改變鏈結方向,改變方向時需要將原本指向後乙個結點的鏈結方向指向前乙個結點,因此需要記錄下三個結點。include using namespace std struct listnode class solution listnode fron...

劍指Offer 15 反轉鍊錶

輸入乙個鍊錶,反轉鍊錶後,輸出鍊錶的所有元素。coding utf 8 class listnode def init self,x self.val x self.next none class solution 返回listnode def reverselist self,phead writ...

劍指offer 15 反轉鍊錶

輸入乙個鍊錶,反轉鍊錶後,輸出鍊錶的所有元素。include using namespace std struct listnode class solution class solution1 return pfront1 else pnode next new listnode num int ...