反转链表

递归实现:

实现逻辑是两个两个进行比较

  1. 找到最后一个节点

  2. 让newHead=最后一个节点

  3. 将最后一个节点的next指向老的head

  4. 将老的next置为null

//递归反转
  reverseList() {
    //1 2
    let head = this.head;
    function reverse(head) {
      //终止条件
      if (head == null || head.next === null) return head;
      const newHead = reverse(head.next); //可以找到链表的最终节点
      head.next.next = head;
      head.next = null;
      return newHead;
    }
    return reverse(head);
  }

while实现反转:

  reverseList() {
    let head = this.head;
    if (head == null || head.next == null) return head;
    let newHead = null;
    while (head) {
      const temp = head.next; //保存第2个节点
      head.next = newHead; //将1指向null
      newHead = head; //将新的链表头指向1
      head = temp; //让老的头指向2
    }
    return newHead;
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值