My easy understand c++ solution with explanation

  • 0

    In this question, you can separate it to many sub-question with no more than two nodes linked list. There are three steps of my solution.

    1. check if it is an empty linked list or there's only one node in the linked list.
    2. do the swapping.
    3. move to the next sub-question.

    Hope this helps.

    class Solution {
        ListNode* swapPairs(ListNode* head) {
            // deal with 1. empty link 2. link with only one node
            if(head == NULL || head->next == NULL)
            {   return head;}
            // swap two nodes
            ListNode* temp = head;
            head = temp->next;
            temp->next = head->next;
            head->next = temp;
            // recursion
            if(temp->next != NULL)
                temp->next = swapPairs(temp->next);
            return head;

Log in to reply

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