劍指OFFER 反轉鍊錶

2021-09-28 16:32:22 字數 1010 閱讀 8497

時間複雜度:o(n)

空間複雜度:o(1)

class

solution

:# 返回listnode

defreverselist

(self, phead):if

not phead:

return phead

else

: head = phead

tail = head.

next

head.

next

=none

while tail:

tail.

next

, tail, head = head, tail.

next

, tail

return head

class solution 

return head;}}

;

時間複雜度:o(n)

空間複雜度:o(…)

class

solution

:# 返回listnode

defreverselist

(self, phead)

:## 終止條件

ifnot phead or

not phead.

next

:return phead

## 遞迴

re_head = self.reverselist(phead.

next

) phead.

next

.next

= phead

phead.

next

=none

## 每輪返回值為已反轉的煉表表頭,即永遠是原鍊錶的表尾

return re_head

class solution 

};

劍指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 ...