1. 程式人生 > >【LeetCode題解】24_兩兩交換連結串列中的節點(Swap-Nodes-in-Pairs)

【LeetCode題解】24_兩兩交換連結串列中的節點(Swap-Nodes-in-Pairs)

目錄

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

描述

給定一個連結串列,兩兩交換其中相鄰的節點,並返回交換後的連結串列。

示例:

給定 1->2->3->4, 你應該返回 2->1->4->3.

說明:

  • 你的演算法只能使用常數的額外空間。
  • 你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

解法一:迭代

思路

這道題的思路其實很直接(改變一對節點的 next 指標),比較難的是該如何進行交換。這裡,我首先生成一個虛擬頭節點 dummy,這樣可以將後面執行的操作統一起來,不用區分是否為連結串列的頭部(head)。接著,藉助於兩個指標 firstsecond,實現兩個節點的“交換”。

Java 實現

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode curr = dummy;
        while (curr.next != null && curr.next.next != null) {
            ListNode first = curr.next;
            ListNode second = curr.next.next;
            
            // swap two nodes
            first.next = second.next;
            second.next = first;
            curr.next = second;
            
            // update to next iteration
            curr = curr.next.next;
        }
        return dummy.next;
    }
}
// Runtime: 2 ms
// Your runtime beats 100.00 % of java submissions.

Python 實現

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

class Solution:
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        dummy = ListNode(-1)
        dummy.next, curr = head, dummy
        while curr.next and curr.next.next:
            first, second = curr.next, curr.next.next
            
            # swap two nodes
            first.next, second.next, curr.next = second.next, first, second
            
            # update to next iteration
            curr = curr.next.next
        return dummy.next
# Runtime: 32 ms
# Your runtime beats 100.00 % of python3 submissions.

複雜度分析

  • 時間複雜度\(O(n)\),其中 \(n\) 表示連結串列的長度(節點的數目)。迴圈需要的次數為 \(\left \lfloor \frac{n}{2} \right \rfloor\),且迴圈中執行的操作的時間複雜度為 \(O(1)\),因此,總的時間複雜度是 \(O(n)\)
  • 空間複雜度\(O(1)\),只需要儲存 4 個節點的引用和一個虛擬頭結點。

解法二:遞迴(不滿足空間複雜度要求)

思路

遞迴的方式也需要改變一對節點的 next 指標,不同的是,遞迴的方式首先遞迴到連結串列的尾部,然後從連結串列的尾部開始交換節點,一直到連結串列的頭部。

Java 實現

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode p = head.next;
        head.next = swapPairs(head.next.next);
        p.next = head;
        return p;
    }
}
// Runtime: 2 ms
// Your runtime beats 100.00 % of java submissions.

Python 實現

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

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

複雜度分析

  • 時間複雜度\(O(n)\),其中 \(n\) 表示連結串列的長度(節點的數目)。
  • 空間複雜度\(O(n)\),遞迴呼叫佔用系統棧空間,遞迴的深度為 \(\left \lfloor \frac{n}{2} \right \rfloor\)