力扣刷题 -- 反转链表

在这里插入图片描述
这是一道面试题,对于这道题我们可以采用递归和迭代(非递归)两种方法实现

递归:传入head如4,反转后为4->3->2->1-null,在串上节点5。
非递归:利用head的next指向newHead,将节点一个一个串起来。

package 链表;

/**
 * https://leetcode-cn.com/problems/reverse-linked-list/
 *
 * @author boyas
 * @create 2021/6/19 0:17
 */
public class _206_反转链表 {
    //采用递归实现
    //假设head节点为5,head.next为4
    public ListNode reverseList(ListNode head) {
        //边界条件
        if (head == null || head.next == null) return head;//节点为空或者单节点反转返回head
        //递归
        ListNode newHead = reverseList(head.next);//传入4,采用递归实现newHead->1->2->3->4>null
        head.next.next = head;//4的next指向5
        head.next = null;//5指向null
        return newHead;//最后返回1->2->3->4->5->null
    }

    //采用非递归实现,一个一个节点串起来
    public ListNode reverseList2(ListNode head) {
        if (head == null || head.next == null) return head;//节点为空或者单节点反转返回head
        ListNode newHead = null;//开始newHead指向null
        //迭代(非递归)利用head的next指向newHead
        while (head != null) {
            ListNode tmp = head.next;//一开始tmp指向head(5)的next(4)
            head.next = newHead;//head(5)的next指向newHead
            newHead = head;//newHead指向head(5)
            head = tmp;//现在head可以指向tmp所指向节点即(4),一个节点串起来了即newHead->5->null
        }//一次循环串一个节点,直至head指向null
        return newHead;//最后返回1->2->3->4->5->null
    }

}

采用递归效率
在这里插入图片描述
采用非递归效率
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

༄༊心灵骇客༣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值