【LeetCode題解】206_反轉鏈表(Reverse-Linked-List)

更多 LeetCode 題解筆記可以訪問我的 github

描述

反轉一個單鏈表。

示例

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

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

解法一:迭代

思路

遍歷鏈表的每個節點,將每個節點的 next 指針指向它的前一個節點(即前驅)。因爲這是一個單向鏈表,並不存在指向前一個節點的引用,因此需要一個變量存儲指向前一個節點的引用。同時,在改變節點的 next 指針之前,還需要另一個變量存儲指向下一個節點的引用。

Java 實現

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode cur = head;
        while (cur != null) {
        	ListNode nextNode = cur.next;
        	cur.next = prev;
        	prev = cur;
        	cur = nextNode;
        }
        return prev;
    }
}

Python 實現

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prev, curr = None, head
        while curr:
            curr.next, prev, curr = prev, curr, curr.next
        return prev

複雜度分析

  • 時間複雜度:O(n)O(n),其中 nn 表示鏈表的節點數
  • 空間複雜度:O(1)O(1)

解法二:遞歸

思路

遞歸的思路和迭代的方式相反,遞歸是從鏈表的尾節點(tail)開始逐一改變節點的 next 指針。因此,遞歸的方式首先會遞歸到鏈表的尾節點,此時遞歸的深度爲 nnnn 表示鏈表的節點數),然後再逐層返回,每次都修改當前節點的 next 指針。

Java 實現

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        
        ListNode p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }
}

Python 實現

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head
        
        p = self.reverseList(head.next)
        head.next.next, head.next = head, None
        return p  

複雜度分析

  • 時間複雜度:O(n)O(n),其中 nn 表示鏈表的節點數
  • 空間複雜度:O(n)O(n),額外的空間是由於遞歸調用佔用系統棧的空間,遞歸的深度最多爲 nn
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章