【LeetCode-鏈表】面試題-反轉鏈表

題目來源於 LeetCode 上第 206號(Reverse Linked List)問題,題目難度爲 Easy,AC率55.2%面試

題目地址:https://leetcode.com/problems/reverse-linked-list/算法

題目描述

Reverse a singly linked list.數組

反轉一個單鏈表bash

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
複製代碼

解法一: 遞歸

  1. 尋找遞歸結束條件:當鏈表只有一個節點,或者若是是空表的話,結束遞歸函數

    head == null || head.next  == null
    複製代碼
  2. 調用函數自己,傳入下一個節點post

    reverseList(head.next);
    複製代碼

    咱們把 2->3->4->5 遞歸成了 5->4->3->2, 對於1節點沒有去更改,因此1的next節點指向的是2,以下所示ui

    遞歸前:
    1 -> 2 -> 3 -> 4 -> 5
    
    遞歸後:
    1 -> 2 <- 3 <- 4 <- 5
         |
         v
        null
    複製代碼
  3. 最後將節點 2 的 next 指向 1,而後把 1 的 next 指向 null,以下所示spa

    null <- 1 <- 2 <- 3 <- 4 <- 5
    複製代碼

算法效率以下圖所示: 3d

-w600

代碼實現

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next  == null) return head;
        
        ListNode nextNode = reverseList(head.next);
        
        ListNode tempNode = head.next;
        tempNode.next = head;
        head.next = null;
        
        return nextNode;
    }
}
複製代碼

解法二: 原地逆置鏈表

設置三個節點 preNode, head, nextcode

  1. 判斷head 以及 head.next 是否爲空,若是爲空,結束循環
  2. 若是不爲空,設置臨時變量next爲head的下一個節點
  3. head的下一個節點指向preNode,而後preNode移動到head, head移動到next
  4. 重複(1)(2)(3)

算法效率以下圖所示:

-w600

代碼實現

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode preNode = null;
        while (head!=null){
            ListNode next = head.next;
            head.next = preNode;
            preNode = head;
            head = next;
        }
        return preNode;
    }
}
複製代碼

解法三:頭插入法逆值鏈表

  1. 新建一個新鏈表, 新鏈表的頭結點 newHead
  2. 循環判斷head是否爲空,爲空時結束循環
  3. 若是不爲空,依次取原鏈表中的每個節點,做爲第一個節點插入到新鏈表中

算法效率以下圖所示:

-w600

代碼實現

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode newHead = new ListNode(0);
        while (head!=null){
            ListNode tempNode = new ListNode(head.val);
            tempNode.next = newHead.next;
            newHead.next = tempNode;
            head = head.next;
        }
        return newHead.next;
    }
}
複製代碼

相關文章

【LeetCode-棧】有效的括號

【LeetCode-鏈表】面試題-反轉鏈表

【LeetCode-二叉樹】二叉樹前序遍歷

【LeetCode-數組】數組式整數加法

相關文章
相關標籤/搜索