给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
输入:head = [1,2]
输出:[2,1]
输入:head = []
输出:[]
提示:
- 链表中节点的数目范围是 [0, 5000]
- -5000 <= Node.val <= 5000
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
};
栈的特点是先进后出,可以利用这个特性来实现反转
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
const stack = []
let current = head
while(current !== null) {
stack.push(current)
current = current.next
}
// 如果链表为空
if (!stack.length) {
return null
}
// pop出来当 head
let node = stack.pop()
let dummy = node
while(stack.length) {
node.next = stack.pop()
node = node.next
}
// 最后的next要设置为空,不然要导致成环
node.next = null
return dummy
};
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let newListNode = null
while(head !== null) {
// 先把下一个节点保存起来
const temp = head.next
// 把下一个节点设置成新的链表
head.next = newListNode
// 把新的链表设置成修改后的节点
newListNode = head
// 链表后移
head = temp
}
return newListNode
};