定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
//剑指offer24.反转链表 javascript
/**
* @param {number[]} nums
* @return {number[]}
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
function ListNode(val) {
this.val = val;
this.next = null;
}
/**
* @param {ListNode} head
* @param {number} k
* @return {T}
*/
// 使用map记录值
const reverseList = function(head) {
if (!head) return null
const map = new Map()
let idx = 1
map.set(0, head.val)
while (head.next) {
map.set(idx, head.next.val ? head.next.val : null)
head = head.next
idx++
}
return Array.from(map.values()).reduce((next, val) => {
return { next, val }
}, null)
};
// 使用数组记录值
const reverseList = function(head) {
if (!head) return null
const arr = [head.val]
while (head.next) {
head.next.val != undefined && arr.push(head.next.val)
head = head.next
}
return arr.reduce((next, val) => {
return { next, val }
}, null)
};
const head = {
val: 1,
next: {
val: 2,
next: {
val: 3,
next: {
val: 4,
next: {
val: 5
}
}
}
}
}
console.log(reverseList(head)) // { next: { next: { next: [Object], val: 3 }, val: 4 }, val: 5 }