Swapping Nodes in Pairs in a Linked List
When solving this problem initially, many developers might skip using a dummy head node and handle the swap directly. Here’s how that works:
- Define two nodes
firstNodeandsecondNodeto represent the adjacent pair being swapped, plus anextPairHeadto store the starting point of the next unprocessed segmant. - After swaping,
firstNodeends up behindsecondNode, so it needs to point to the correct next node: if the next segment has at least two nodes, it points to the swapped head of that segment (the original second node of the next pair); if there’s 0 or 1 node left, it points directly to that remaining node. - Handle edge cases: even-length lists swap all pairs, while odd-length lists stop after processing the last complete pair and leave the final single node untouhced.
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode* firstNode = head;
head = head->next;
while (firstNode != nullptr && firstNode->next != nullptr) {
ListNode* secondNode = firstNode->next;
ListNode* nextPairHead = secondNode->next;
secondNode->next = firstNode;
if (nextPairHead != nullptr && nextPairHead->next != nullptr) {
firstNode->next = nextPairHead->next;
} else {
firstNode->next = nextPairHead;
}
firstNode = nextPairHead;
}
return head;
}
};
A more efficient and cleaner approach uses a dummy head node. This technique eliminates the need for separate handling of the head node and simplifies the logic for updating pointers after each swap.
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* current = dummyHead;
while (current->next != nullptr && current->next->next != nullptr) {
ListNode* prevSegTail = current;
ListNode* firstInPair = current->next;
ListNode* secondInPair = current->next->next;
ListNode* nextSegHead = secondInPair->next;
prevSegTail->next = secondInPair;
secondInPair->next = firstInPair;
firstInPair->next = nextSegHead;
current = firstInPair;
}
return dummyHead->next;
}
};