劍指offer 反轉鍊錶

2021-10-05 09:35:01 字數 699 閱讀 9505

定義了乙個新的煉表頭,在掃瞄原鍊錶的時候,將掃瞄到的節點用頭插法插入新的煉表頭後面。之後新的煉表頭的next指向的就是反轉的鍊錶的第乙個節點。

# -*- coding:utf-8 -*-

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class

solution

:# 返回listnode

defreverselist

(self, phead)

:# write code here

if phead is

none

:return phead

head = listnode(0)

pnow = phead

while pnow is

notnone

: pnext = pnow.

next

pnow.

next

= head.

next

head.

next

= pnow

pnow = pnext

return head.

next

劍指offer 反轉鍊錶

輸入乙個鍊錶,反轉鍊錶後,輸出鍊錶的所有元素。方法1 將單鏈表儲存為陣列,然後按照陣列的索引逆序進行反轉。方法2 使用三個指標遍歷單鏈表,逐個鏈結點進行反轉。方法3 從第2個節點到第n個節點,依次逐節點插入到第1個節點 head節點 之後,最後將第乙個節點挪到新錶的表尾。public class l...

劍指offer 反轉鍊錶

輸入乙個鍊錶,反轉鍊錶後,輸出鍊錶的所有元素。1.非遞迴 struct listnode class solution listnode ppre null listnode p phead listnode pnext null while p null else p pnext return p...

《劍指offer》 反轉鍊錶

輸入乙個鍊錶,反轉鍊錶後,輸出鍊錶的所有元素。之前錯誤的寫法,一直不明白 原因是移位的時候,pcurr移到下一位時,裡面的值已經變成反向指標了,所以不能成功移動,就迴圈巢狀進去了,所以還需要乙個變數pnext來儲存移位前的值。struct listnode class solution phead ...