【LeetCode】206. Reverse Linked List 解題報告
206. Reverse Linked List / Easy
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
Solution
思路
如果要 in-place 反轉整個 linked list,就必須要每一步都將 node 之間的指標反轉。
至少會需要三個指標,一個指向前面,一個指向後面,另一個則是目前節點的指標。
直接看程式碼,很直白。
效能
Complexity
- Time Complexity: O(N), where N is the length of the linked list
- Space Complexity: O(1)
LeetCode Result
- Runtime: 11 ms
- Memory Usage: 8.3 MB
- https://leetcode.com/submissions/detail/711920523/
Code
1 | class Solution { |