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

    在这里插入图片描述

  • 相关阅读:
    最新Xcode7.x环境下上架iOS App到AppStore 完整流程
    rails提供的validators
    Ruby 符号【转】
    xaml学习笔记
    fedora安装rails缺少js runtime和cannot load such file -- sqlite3/sqlite3_native解决办法
    学习笔记——敏捷开发
    结队编程(电梯调度问题)
    【转】javascript操作Select标记中options集合
    【软件工程】Word frequency program
    【转】诗社之死
  • 原文地址:https://www.cnblogs.com/pjhaymy/p/13767046.html
Copyright © 2011-2022 走看看