zoukankan      html  css  js  c++  java
  • 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刷题系列,我会每日一更或者每日多更,想一起刷题的小可爱们可以私信或者关注我我们一同学习

    在这里插入图片描述

  • 相关阅读:
    阿里P8架构师谈:阿里双11秒杀系统如何设计?
    秒杀系统设计的知识点
    秒杀系统架构优化思路
    秒杀系统解决方案
    Entity Framework Code First (七)空间数据类型 Spatial Data Types
    Entity Framework Code First (六)存储过程
    Entity Framework Code First (五)Fluent API
    Entity Framework Code First (四)Fluent API
    Entity Framework Code First (三)Data Annotations
    Entity Framework Code First (二)Custom Conventions
  • 原文地址:https://www.cnblogs.com/pjhaymy/p/13767046.html
Copyright © 2011-2022 走看看