Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Swapping Nodes in Pairs in a Linked List

Tech 1

When solving this problem initially, many developers might skip using a dummy head node and handle the swap directly. Here’s how that works:

  1. Define two nodes firstNode and secondNode to represent the adjacent pair being swapped, plus a nextPairHead to store the starting point of the next unprocessed segmant.
  2. After swaping, firstNode ends up behind secondNode, 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.
  3. 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;
    }
};

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.