链表的逆置
简介
本文将介绍如何逆转一个链表。链表是一种常见的数据结构,由一系列节点组成,每个节点包含数据和指向下一个节点的指针。逆转链表意味着将链表中所有节点的指针方向反转,使得原来的头节点变为尾节点,原来的尾节点变为头节点。
示例
链表:node1 -> node2 -> node3 -> node4 -> node5
逆置:node5 -> node4 -> node3 -> node2 -> node1
实现方法
方法一:递归
递归方法通过递归调用自身来逆转链表。递归的终止条件是当链表为空或只有一个节点时,直接返回头节点。否则,递归处理当前节点的下一个节点,并在递归返回后调整当前节点和其下一个节点的指针方向。
class Node {
constructor(val) {
this.val = val
this.next = null
}
}
let node1 = new Node(1)
let node2 = new Node(2)
let node3 = new Node(3)
let node4 = new Node(4)
let node5 = new Node(5)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = null
function reverseList(head) {
// 倒数第二个节点
if (head.next.next == null) {
head.next.next = head // 最后一个节点指向倒数第二个节点
return head.next
} else {
// 递归处理当前其余节点
let result = reverseList(head.next)
// 递归结束后,处理最后一个节点,让最后一个节点的下个节点的next指向自己,自己指向null
head.next.next = head
head.next = null
// 返回新的头节点
return result
}
}
let newRoot = reverseList(node1)
function bianLink(root) {
if (root == null) return
console.log(root.val)
bianLink(root.next)
}
bianLink(newRoot)
方法二:AI提供
class Node {
constructor(val) {
this.val = val
this.next = null
}
}
let node1 = new Node(1)
let node2 = new Node(2)
let node3 = new Node(3)
let node4 = new Node(4)
let node5 = new Node(5)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = null
function reverseList(head) {
// 如果链表为空或只有一个节点,直接返回头节点,因为反转后的结果还是它本身
if (!head || !head.next) return head
// 初始化两个指针,prev指向null,curr指向链表的头节点
let prev = null
let curr = head
// 遍历链表,直到curr为null,即到达链表的末尾
while (curr) {
// 保存当前节点的下一个节点
let next = curr.next
// 将当前节点的next指针指向prev,实现反转
curr.next = prev
// 将prev和curr指针向后移动一位
prev = curr
curr = next
}
// 当curr为null时,prev指向反转后的链表的头节点
return prev
}
let newRoot = reverseList(node1)
function bianLink(root) {
if (root == null) return
console.log(root.val)
bianLink(root.next)
}
bianLink(newRoot)