敘述
這是 Algorithm I 的第十天第二個題目,總共有兩題。
- 難度:
Easy - 花費時間: 5 min
- 題目
給你一個 Linked List 將其反轉之後回傳。
點我開啟限制與範例
限制:
- The number of nodes in the list is the range
[0, 5000]. -5000 <= Node.val <= 5000
Example 1:

1 | Input: head = [1,2,3,4,5] |
Example 2:

1 | Input: head = [1,2] |
Example 3:
1 | Input: head = [] |
筆記
這題沒什麼限制,所以應該很多方法都可以做,這邊提供兩個方法
1. Array iterative
這是我自己想到的方法,我相信也是相對直觀的。
- 遍歷
Linked-list把所有的Node存進Array - 從
Array的最後一個值開始,把next指向Array的上一個值。
TypeScript
1 | function reverseList(head: ListNode | null): ListNode | null { |
2. In-place iterative
有點類似 two-pointers 的概念
- 宣告兩個指針存取當前的
head跟head.next=nextHead - 宣告一個
tempNode佔存nextHead.next nextHead.next指向haedhead往後推nextHead往後推- 重複上述步驟直到
nextHead == null
Java
1 | public ListNode reverseList(ListNode head) { |
還有 recursion 版本的,但是都大同小異,就等下次遇到這個題目再來做就好。
成績
