1. 程式人生 > 實用技巧 >Leetcode刷題 206. 反轉連結串列 遞迴迭代兩種方法實現

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刷題系列,我會每日一更或者每日多更,想一起刷題的小可愛們可以私信或者關注我我們一同學習