DAY 10
1
Software Development

## LeetCode 雙刀流：206. Reverse Linked List

### 先看一下題目描述

Given the head of a singly linked list, reverse the list, and return the reversed list.

### 再搭配範例理解題目

• Example 1:
``````Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
``````
• Example 2:
``````Input: head = [1,2]
Output: [2,1]
``````

## 開始實作

### 方法 ①：交換法

``````head.next = prev
``````

• prev：指向前一個

#### 那我們先用 Python 實作看看

``````class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
return prev

``````

#### 也可以用 JavaScript 復刻一次

``````var reverseList = function(head) {
let prev = null;
}
return prev;
};
``````

``````# Python

# JavaScript
``````

### 方法 ②：遞迴（recursion）

#### 那我們先用 Python 實作看看

``````class Solution:
def reverseList(self, head: Optional[ListNode], prev=None) -> Optional[ListNode]:
``````

#### 也可以用 JavaScript 復刻一次

``````var reverseList = function(head, prev=null) {
let next = head.next; // 先把下一個記起來
};
``````

## 反思沉澱

### 1 則留言

0
TD
iT邦新手 4 級 ‧ 2021-09-25 22:12:06