• Leetcode刷题 206. 反转链表 递归迭代两种方法实现


    题目链接

    链接https://leetcode-cn.com/problems/reverse-linked-list/

    题目描述

    反转一个单链表。

    示例:

    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL

    进阶:
    你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

    预置代码

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode reverseList(ListNode head) {
             
        }
    }
    

    解题思路

    方法一:递归实现

    未反转前
    在这里插入图片描述
    反转后

    在这里插入图片描述
    构造一个函数reverseList(ListNode head)进行链表反转

    
        public ListNode reverseList(ListNode head) {
            /*如果传入的节点等于null则之间返回head说明只有一个,无需反转*/
            if (head==null){
                return  head;
            }
            /*如果传入节点的下一个节点为null,说明递归结束,开始进行返回节点*/
            else if (head.next==null){
                return head;
            }
            /*进行递归循环,newHead保存的是最后一个节点的位置*/
            ListNode newHead = reverseList(head.next);
            /*传入的head节点的后继节点的next指向head,实现反转*/
            head.next.next=head;
            /*head的next=null*/
            head.next=null;
            return  newHead;
        }
    
    

    精解后的代码

    public ListNode reverseList(ListNode head) {
            if (head==null||head.next==null){
                return  head;
            }
            ListNode newHead = reverseList(head.next);
            head.next.next=head;
            head.next=null;
            return  newHead;
        }
    

    大家如果觉得光看代码难以理解可以通过边画图边读代码的方式来进行理解,这样我感觉学起来更容易

    方法二:迭代

    这个理解起来应该比递归要容易的多

    public ListNode reverseList(ListNode head) {
            /*如果head==null或则head.next==null,
            即说明只有一个或者零个元素的时候,则不用经行反转
            ,直接返回head*/
            if (head.next==null||head==null){
                return head;
            }
            /*新的链表的头节点*/
            ListNode newHead=null;
            while(head!=null){
               ListNode temp=head.next;
               head.next=newHead;
               newHead=head;
               head=temp;
            }
           return newHead;
        }
    

    图片演示

    在这里插入图片描述
    第一次移动

    在这里插入图片描述
    第二次

    在这里插入图片描述
    以此类推不再做演示

    这是博主的Leetcode刷题系列,我会每日一更或者每日多更,想一起刷题的小可爱们可以私信或者关注我我们一同学习

    在这里插入图片描述

  • 相关阅读:
    ASP.NET MVC路由规则
    VS2013 修改TFS的本地映射路径
    新安装的VS的一些设置
    ASP.NET MVC验证标注的扩展-checkbox必选
    进入做Mvc项目的时候 返现某个文件夹下面css js png等静态文件都访问不了
    Mac入门 (二) 使用VMware Fusion虚拟机
    Mac入门(一)基本用法
    软件测试面试 (二) 如何测试网页的登录页面
    软件测试面试 (一) 如何测试一个杯子
    Python自动化测试 (二) ConfigParser模块读写配置文件
  • 原文地址:https://www.cnblogs.com/pjhaymy/p/13767046.html
Copyright © 2020-2023  润新知