看一百遍美女,美女也不一定是你的。但你刷一百遍算法,知识就是你的了~~
谁能九层台,不用累土起!
题目
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
示例一:
输入: head = [1,2,3,4,5]
输出: [5,4,3,2,1]
示例二:
输入: head = [1,2]
输出: [2,1]
示例三:
输入: head = []
输出: []
提示
- 链表中节点的数目范围是
[0, 5000]
-5000 <= Node.val <= 5000
解题思路
- 最后一项的
next
一定是null
,因为当前的第一项为结果的最后一项,因此有head.next=null
- 我们接下来通过修改next的指向来解题(第二项的
next
原本指向3
,我们将其指向2
)
- 后面的逻辑就跟第二步一样了
解题代码
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
};
如有任何问题或建议,欢迎留言讨论!