Algorithem_ReverseLinkedList
Given the head of a singly linked list, reverse the list, and return the reversed list.
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
1 | Input: head = [1,2,3,4,5] |
Example 2:
1 | Input: head = [1,2] |
Example 3:
1 | Input: head = [] |
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?
解法一
先撇开 followup,最直接的解法时,我把 LinkNode 转为数组,然后数组逆序,再生成新的 LinkNode
代码如下:
1 |
|
解法二
这里理解比较麻烦,可参考,Reverse a linked list,页面最下方的视频,多看几遍。
迭代解法:
- 声明三个指针,prev = nil, current = head, next = nil,
- 循环遍历LinkedList
- 改变 next 前,先保存 next,设置 next = current.next
- 然后改变 next,这一步是 reverse 的关键,设置 current.next = prev
- 然后 prev 和 current 向下个节点移动,设置 prev = current, current = next
代码如下:
1 |
|
解法三
递归解法:另一种不同的理解,Reverse Linked List
重要是改变next指针指向,而不是赋不同的值
- 声明两个ListNode,prev 和 temp
- prev 用于代表前一个,temp 代表暂时存储的,加上 mutHead 当前的,一共还是三个 ListNode
- 循环,mutHead 不为空,
- temp = mutHead,把 temp赋值为当前
- mutHead = mutHead.next,把 mutHead赋值为下一个
- temp.next = prev,把 temp 的 next 指向 prev,注意此时 temp 的值是当前,即当前的下一个是 prev,指针的方向就实现了反过来了
- prev = temp,把 prev 赋值为 temp,即 prev 赋值为当前,然后继续下一次遍历,知道 mutHead 为空停止
代码如下:
1 |
|
解法四
递归解法,参考 reclusive reverse linked list,
主要需要理解:
递归中每一步赋值 curr.next.next = curr 和 curr.next = nil 两步
1 |
|