更多 LeetCode 題解筆記可以訪問我的 github。
描述
給定一個鏈表,兩兩交換其中相鄰的節點,並返回交換後的鏈表。
示例:
給定 1->2->3->4, 你應該返回 2->1->4->3.
說明:
- 你的算法只能使用常數的額外空間。
- 你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
解法一:迭代
思路
這道題的思路其實很直接(改變一對節點的 next
指針),比較難的是該如何進行交換。這裏,我首先生成一個虛擬頭節點 dummy
,這樣可以將後面執行的操作統一起來,不用區分是否爲鏈表的頭部(head)。接着,藉助於兩個指針 first
和 second
,實現兩個節點的“交換”。
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.
複雜度分析
- 時間複雜度:,其中 表示鏈表的長度(節點的數目)。循環需要的次數爲 ,且循環中執行的操作的時間複雜度爲 ,因此,總的時間複雜度是 。
- 空間複雜度:,只需要存儲 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
複雜度分析
- 時間複雜度:,其中 表示鏈表的長度(節點的數目)。
- 空間複雜度:,遞歸調用佔用系統棧空間,遞歸的深度爲 。