题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
本来感觉自己写的不太好,不想分享思路了但是一看题解千篇一律的都是双指针加while循环,我觉得我还是有必要分享一下我的想法,毕竟和其他的题解不太一样。
基本思路是利用了数组和单向链表的特性不同实现的,数组可以直接索引元素,而且没有方向性可以直观实现反转这个操作。
先定义一个读取链表的方法,递归调用将链表值存到一个数组里
之后再将这个数组反向做出栈操作,用pop方法实现,递归生成一个新的链表
function ReverseList(pHead)
{
// write code here
if (!pHead) return null
let arr = []
function readList (node) {
arr.push(node.val)
if (node.next) {
readList(node.next)
}
return
}
readList(pHead)
function createList (arr) {
let node = new ListNode(arr.pop())
if (arr.length) {
node.next = createList(arr)
}
return node
}
let res = createList(arr)
return res
}
module.exports = {
ReverseList : ReverseList
};