定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
链表的反转实际上是将链表的指针反转
原链表:
反转后:
分析
遍历链表,既然需要反转,那么就需要记录前一个节点的指针 pre,然后将当前的 next 与 pre 进行交换,实现一个节点的反转
要实现全部节点的反转可以使用递归以此类推或简单实用 while 迭代,仅仅记录 pre 即可实现
迭代法:
class NodeList {
constructor(val) {
this.val = val
this.next = null
}
//添加链表的新增节点方法
append(val) {
let currnt = this
let node = new NodeList(val)
while (currnt.next) {
currnt = currnt.next
}
currnt.next = node
}
// 打印
print() {
let current = this
let res = []
while (current) {
res.push(current.val)
current = current.next
}
console.log(res)
}
}
let node1 = new NodeList(1)
node1.append(2)
node1.append(6)
node1.append(8)
const f = (head) => {
let cur = head
let pre = null
while (cur) {
const next = cur.next
cur.next = pre
pre = cur
cur = next
}
return pre
}
console.log(`翻转前:`)
node1.print()
console.log(`翻转后:`)
f(node1).print()
输出结果:
翻转前: [ 1, 2, 6, 8 ] 翻转后: [ 8, 6, 2, 1 ]