Very simple recursive C++ solution

  • 1

    In such questions it is generally easy to write recursive solutions.
    You need to consider the edge cases first.
    What if the list contains no element or only one element. Then the result will be the same as the input.
    For example :
    List : 1
    swapPairs(1) = 1;
    For a general case :
    List l: a,b,c,d,e,f,g,h,i
    swapPairs(l) = b->a->swapPairs(c,d,e,f,g,h,i)
    That is what my code is doing.

    class Solution {
        ListNode* swapPairs(ListNode* head) {
            if(!head || !head->next)
                return head;
            ListNode * temp = head->next;
            head->next = swapPairs(temp->next);
            temp->next = head;
            return temp;

  • 0

    helpful,thanks for sharing!

Log in to reply

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