206. Reverse Linked List
...大约 1 分钟
给你单链表的头节点
head
,请你反转链表,并返回反转后的链表。示例 1:
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2] 输出:[2,1]
示例 3:
输入:head = [] 输出:[]
提示:
- 链表中节点的数目范围是
[0, 5000]
-5000 <= Node.val <= 5000
1. 迭代
需要三个变量: prev
前一节点, next
下一节点, cur
当前节点
- 对于当前节点
cur
, 暂存其下一个节点next = cur.Next
- 反转
cur.Next = prev
- 更新当前和前一操作节点:
prev = cur
,cur = next
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
cur := head
for cur != nil {
next := cur.Next
cur.Next = prev
prev = cur
cur = next
}
return prev
}
2. 递归
对于节点i
, 其前面的节点都已经反转, 只需反转当前节点即可. 如当前节点为空或者是尾节点则结束反转.
反转当前节点时:
- 下一节点指向当前节点
- 当前节点的下一节点置空(当前节点为头节点时, 反转后的节点一定指向
nil
)
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
newHead := reverseList(head.Next)
head.Next.Next = head
head.Next = nil
return newHead
}
Powered by Waline v2.15.2