LeetCode 筆記 - 206. Reverse Linked List

題目在此 206. Reverse Linked List

給定一個 Linked list,請反轉它

解題思維

這題筆者是多一個 最後一個 node 參數,一個一個指回去,沒什麼特別的技巧

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:

def walk(last, current) -> Optional[ListNode]:
if current is None:
return last

next_temp = current.next
current.next = last

return walk(current, next_temp)
return walk(None, head)

也許你也會想看看