LeetCode 206:反轉鏈表 Reverse Linked List

反轉一個單鏈表。java

Reverse a singly linked list.python

示例:函數

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

進階: 你能夠迭代或遞歸地反轉鏈表。你可否用兩種方法解決這道題?code

Follow up:對象

A linked list can be reversed either iteratively or recursively. Could you implement both?遞歸

解題思路:

每次遍歷到最後一位取節點這種方法就算了時間複雜度過高。如題目進階要求的兩種方法,迭代和遞歸:it

迭代:

每次分出來一個節點把節點做爲頭節點添加到新鏈表上:io

原鏈表:1->2->3->4->5class

分離第一個節點做爲頭節點添加到新鏈表:1 原鏈表:2->3->4->5原理

分離下一個節點做爲頭節點添加到新鏈表:2->1 原鏈表:3->4->5

分離下一個節點做爲頭節點添加到新鏈表:3->2->1 原鏈表:4->5

分離下一個節點做爲頭節點添加到新鏈表:4->3->2->1 原鏈表:5

分離下一個節點做爲頭節點添加到新鏈表:5->4->3->2->1 原鏈表:null

Java:

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode pre = null;
        ListNode tmp = null;
        while (head != null) {
            tmp = head.next;//tmp暫存當前節點的下一個節點
            head.next = pre;//當前節點下一個指向pre
            pre = head;//刷新pre
            head = tmp;//刷新當前節點爲tmp
        }
        return pre;
    }
}

Python3:

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        pre,tmp=None,None
        while(head):
            tmp=head.next
            head.next=pre
            pre=head
            head=tmp
        return pre

遞歸:

其實就是用遞歸完成棧的功能:先進後出

基線條件爲遇到空節點(到鏈表末尾),返回對象爲鏈表的最後一個節點,在遞歸函數中傳遞一直不變。從鏈表末尾向頭部逐個分離節點,並將節點添加到新鏈表的末尾。與迭代法原理類似。

原鏈表:1->2->3->4->5

遞歸到最後一層時遇到null節點返回尾節點5

回到上一層遞歸 分離節點 5 做爲新鏈表的尾節點:5,置空本來5節點,原鏈表1->2->3->4->null

回到上一層遞歸 分離節點 4 做爲新鏈表的尾節點:5->4,置空本來4節點,原鏈表1->2->3->null

回到上一層遞歸 分離節點 3 做爲新鏈表的尾節點:5->4->3,置空本來3節點,原鏈表1->2->null

回到上一層遞歸 分離節點 2 做爲新鏈表的尾節點:5->4->3->2,置空本來2節點,原鏈表1->null

回到上一層遞歸 分離節點 1 做爲新鏈表的尾節點:5->4->3->2->1,置空本來1節點,原鏈表null

Java:

class Solution {
    public ListNode reverseList(ListNode head) {
        //基線條件
        if (head == null || head.next == null) return head;
        //遞歸
        ListNode tmp = head.next;//暫存頭節點的下一個節點
        ListNode pre = reverseList(head.next);//遞歸調用該函數,pre爲返回的新鏈表的頭節點,原鏈表的最後一個節點,不管遞歸多少層該返回值一直傳遞不變
        tmp.next = head;//暫存的下一個節點指向傳入節點
        head.next = null;//下一個節點即本來指向tmp的節點 置空
        return pre;
    }
}

Python3:

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        tmp = head.next
        pre = self.reverseList(head.next)
        tmp.next = head
        head.next = None
        return pre

歡迎關注公.衆號一塊兒刷題:愛寫Bug

愛寫Bug.png

相關文章
相關標籤/搜索