SoFunction
Updated on 2025-03-09

C++ implements LeetCode (24. Paired Switch Node)

[LeetCode] 24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example:

Given

1->2->3->4

, you should return the list as

2->1->4->3.

This question is not difficult, it is a basic linked list operation question, which we can implement using recursion and iteration respectively. For iterative implementation, it is still necessary to establish a dummy node. Note that when connecting nodes, it is best to draw a picture to avoid making yourself dizzy. See the code as follows:

Solution 1:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode *dummy = new ListNode(-1), *pre = dummy;
        dummy->next = head;
        while (pre->next && pre->next->next) {
            ListNode *t = pre->next->next;
            pre->next->next = t->next;
            t->next = pre->next;
            pre->next = t;
            pre = t->next;
        }
        return dummy->next;
    }
};

The way of writing recursion is more concise. In fact, it uses the idea of ​​backtracking to recursively traverse to the end of the linked list, then first exchange the last two, and then exchange them forward in turn:

Solution 2:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode *t = head->next;
        head->next = swapPairs(head->next->next);
        t->next = head;
        return t;
    }
};

Solution three:

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null ||  == null) {
            return head;
        }
        ListNode newHead = ;
         = swapPairs();
         = head;
        return newHead;
    }
}

This is the article about C++ implementation of LeetCode (24. Paired Switch Nodes). For more related contents of C++ implementation of paired Switch Nodes, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!