leetcode 206 反轉鍊錶

2022-06-24 04:03:09 字數 1936 閱讀 3566

反轉乙個單鏈表。

示例:輸入: 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:

ls=while(head):#壓棧

head=head.next

p1=p2=listnode(0,none)

while(ls):

t=ls.pop()

p2.next=t

p2=p2.next

p2.next=none

return p1.next

# 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:

ls=if not head or not head.next :

return head

while(head):

head=head.next

p=p1=ls.pop()

while(ls):

p.next=ls.pop()

p=p.next

p.next=none

return p1

# 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:

p=none#建立空節點

while(head):

t=head.next#當前節點的下乙個

head.next=p#當前節點的next

p=head#後移

head=t#後移

return p

# 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:

#遞迴if not head or not head.next:

return head

t=self.reverselist(head.next)

head.next.next=head

head.next=none

return t

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