一文彻底搞懂反转链表(JS—递归实现)

1. 先上代码:先准备好一个 1 2 3  的链表 temp

function ListNode(val, next) {
    this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
}

let temp = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode)));

2. 铺垫一下知识,请看如下问题:定义两个不相关的节点node_A 和 node_B,可以自己run一下。

let node_A = new ListNode(1);

let node_B = new ListNode(2);

let temp = node_A

temp.next = node_B

那么 node_A.next ?

    答案: 输出 node_B。


3. 能理解上面这一点,下面反转也就很好理解了。先附上完整的反转代码:

function ListNode(val, next) {
    this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
}

let head = new ListNode(1, new ListNode(2, new ListNode(3)));


let reverseList = function(head) {
    if (head == null || head.next == null) {
        return head;  // 如果链表只有一个元素或者是空链表,我们直接返回
    }
    let newHead = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return newHead;
}

reverseList(head)

理解一下这个递归过程

借助引用类型数据的特性和递归的特性。
       


        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值