C++ Implementation, easy to understand

  • 0

    So basically the idea is to use 3 pointers:
    pPPrev (points to the current 2-node pair)
    pPrev (points to the first node in the original 2-node pair)
    pNode (points to the second node in the original 2-node pair)

    Stop condition: only 1 node left / no nodes left

    class Solution {
        ListNode* swapPairs(ListNode* head) {
            if (head==NULL || head->next==NULL)
                return head;
            ListNode* pseudo_head = new ListNode(0);
            pseudo_head->next = head;
            ListNode* pPPrev = pseudo_head;
            ListNode* pPrev = pseudo_head->next;
            ListNode* pNode = NULL;
            while (pPrev && pPrev->next) {
                pNode = pPrev->next;
                pPrev->next = pNode->next; // Change order
                pNode->next = pPrev;
                pPPrev->next = pNode;
                pPPrev = pPrev; // Move on to the next pair of nodes
                pPrev = pPPrev->next;
            return pseudo_head->next;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.