leetcode 206 反轉鍊錶 easy

2022-08-23 23:39:13 字數 1045 閱讀 1515

反轉乙個單鏈表。

示例:輸入: 1->2->3->4->5->null

輸出: 5->4->3->2->1->null

高階:你可以迭代或遞迴地反轉鍊錶。你能否用兩種方法解決這道題?

迭代:

#

definition for singly-linked list.

#class listnode:

#def __init__(self, x):

#self.val = x

#self.next = none

class

solution:

def reverselist(self, head: listnode) ->listnode:

#遍歷每一步

ifnot head or

nothead.next:

return

head

#注意p1為空值,不是listnode空

p1 =none

p2 =head

#p1指向none p2指向head,反轉後更新到下兩個

while

p2: nextnode =p2.next

p2.next =p1

p1 =p2

p2 =nextnode

return p1

遞迴:

class

solution:

def reverselist(self, head: listnode) ->listnode:

#考慮當前反轉的鍊錶為其next node後的反轉鍊錶和當前node和next node的反轉

ifnot head or

nothead.next:

return

head

nexthead =self.reverselist(head.next)

head.next.next =head

#當前節點的下乙個必須為空,不然會產生迴圈

head.next =none

return nexthead

leetcode 206 鍊錶反轉

一 題目大意 反轉乙個單鏈表,實現遞迴和非遞迴兩種形式 二 鍊錶節點 public class listnode 三,分析 1,非遞迴解決方案 最容易想到的是使用三個指標,p1,p2,p3,遍歷鍊錶事項反轉。這裡需要注意的是,p1,p2,p3的初始化,不同初始化應該考慮煉表頭的不同處理。一般的初始是...

LeetCode 206 反轉鍊錶

反轉乙個單鏈表。高階 鍊錶可以迭代或遞迴地反轉。你能否兩個都實現一遍?設定三個指標分別指向連續的三個節點,每次完成節點的反向就把三個節點同時後移,直到所有節點反轉。definition for singly linked list.struct listnode class solution ret...

LeetCode 206 反轉鍊錶

206.反轉鍊錶 反轉乙個單鏈表。輸入 1 2 3 4 5 null 輸出 5 4 3 2 1 null非遞迴解法 1.class solution object defreverselist self,head type head listnode rtype listnode res none ...