王廷瑋|數位醫療|智慧醫療: 24. Swap Nodes in Pairs WFU

2024年7月2日 星期二

24. Swap Nodes in Pairs

24. Swap Nodes in Pairs


給定一個鏈表,交換每兩個相鄰的節點並返回其頭節點。你必須在不修改節點值的情況下解決這個問題(即,只能改變節點本身)。

範例 1:

輸入:head = [1,2,3,4] 輸出:[2,1,4,3]

Python

from typing import Optional

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

class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
# Create a dummy node to simplify edge cases
dummy = ListNode(0)
dummy.next = head
current = dummy

while current.next and current.next.next:
# Initialize the nodes to be swapped
first = current.next
second = current.next.next
# Perform the swap
first.next = second.next
second.next = first
current.next = second
# Move the pointer forward for the next pair
current = first
# Return the new head, which is dummy.next
return dummy.next

16.13MB, 30ms


C++


/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
// Create a dummy node to simplify edge cases
ListNode dummy(0);
dummy.next = head;
ListNode* current = &dummy;

while (current->next != nullptr && current->next->next != nullptr) {
// Initialize the nodes to be swapped
ListNode* first = current->next;
ListNode* second = current->next->next;
// Perform the swap
first->next = second->next;
second->next = first;
current->next = second;
// Move the pointer forward for the next pair
current = first;
}
// Return the new head, which is dummy.next
return dummy.next;
}
};

9.5MB, 2ms


Javascript


/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val);
* this.next = (next===undefined ? null : next);
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
// Create a dummy node to simplify edge cases
let dummy = new ListNode(0);
dummy.next = head;
let current = dummy;

while (current.next !== null && current.next.next !== null) {
// Initialize the nodes to be swapped
let first = current.next;
let second = current.next.next;
// Perform the swap
first.next = second.next;
second.next = first;
current.next = second;
// Move the pointer forward for the next pair
current = first;
}
// Return the new head, which is dummy.next
return dummy.next;
};

48.91MB, 52ms