【算法】js链表逆置

320 阅读1分钟

首先使用递归函数一直递归到最后一个节点,反转之后该节点就为头部节点。之后,让当前节点的下一个节点的next指针指向当前节点,同时让当前节点的next指针指向NULL,从而实现从尾部开始的反转。递归结束即反转完毕。

dacd1bf55dec5c8b38d0904f26e472e2024fc8bee4ea46e3aa676f340ba1eb9d-递归.gif

function Node(value) {
    this.value = value;
    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;

// 获取最后一个节点
// function lastNode(node) {
    // if(node.next.next == null) return node.next
   // else return lastNode(node.next)
// }
// console.log(lastNode(node1))

// 递归逆置
// function nizhi(root) {
    // if(root.next.next == null) { 
        // console.log("只执行一次,作用是逆转最后一个节点")
        // root.next.next = root;
    // }else {
        // nizhi(root.next);
        // console.log(`逆转node1-node4`)
        // root.next.next = root;
        // root.next = null;
    // }
// }
// nizhi(node1)
// console.log(node1, node2, node3)


// 递归逆置并遍历获取逆转后的结果
function nizhi(root) {
    if(root.next.next == null) { 
        root.next.next = root; 
        return root.next
    }else {
        let result = nizhi(root.next);
        root.next.next = root;
        root.next = null;
        return result;
    }
}
// nizhi(node1)
const newRoot = nizhi(node1);

function bianLi(root) {
    if(root == null) return;
    console.log(root.value);
    bianLi(root.next)
}
// bianLi(node5)
bianLi(newRoot)