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]
Example 3:
Input: head = [] Output: []
Constraints:
- The number of nodes in the list is the range
[0, 5000]
. -5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
SOL:
準備面試跟考試或寫作業,最大的差異是,看到
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
不能假裝沒看到QQ
因為面試的時候,面試官會真的想知道你可不可以implement both
我的刷題列表 Leetcode面试高频题分类刷题总结 有提到,反轉鏈表可以直接背,因此可以感受出他的重要性了!
這一題我的參考影片是:Reverse Linked List | In-place Reversal of a LinkedList 基礎概念 1 網紅高頻題 - Python - LeetCode 206
iteratively 跟 recursively 兩種都有講解,而且iteratively還有教你怎麼背,非常貼心XD
我的程式碼:
- iteratively
一開始需要宣告 prev 為 None 來做為反轉的最後結尾,注意prev不是ListNode,若宣告prev=ListNode(),反而會在最後多接一個0。
- recursively