LeetCode-206-反转链表

看一百遍美女,美女也不一定是你的。但你刷一百遍算法,知识就是你的了~~

谁能九层台,不用累土起!

题目地址

题目

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例一:

image.png

1
2
输入: head = [1,2,3,4,5]
输出: [5,4,3,2,1]

示例二:

image.png

1
2
输入: head = [1,2]
输出: [2,1]

示例三:

1
2
输入: head = []
输出: []

提示

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000

解题思路

image.png

  • 最后一项的next一定是null,因为当前的第一项为结果的最后一项,因此有head.next=null

image.png

  • 我们接下来通过修改next的指向来解题(第二项的next原本指向3,我们将其指向2)

image.png

  • 后面的逻辑就跟第二步一样了

解题代码

1
2
3
4
5
6
7
8
9
10
11
12
var reverseList = function(head) {
if(!head||!head.next) return head
let current = head.next
head.next = null
while (current){
let b = current.next
current.next = head
head = current
current = b
}
return head
};
文章作者: Joker
文章链接: https://qytayh.github.io/2021/12/LeetCode-206-%E5%8F%8D%E8%BD%AC%E9%93%BE%E8%A1%A8/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Joker's Blog