Home > Mobile >  Swap two ListNode* in C
Swap two ListNode* in C

Time:05-21

Please help, I am totally lost here. This is leetcode problem no. 24, swap nodes in pairs. I am getting this error in screeshot.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    void recurse(ListNode* head){
        if(head!=nullptr and head->next!=nullptr){
            auto previous = head, current = head->next;
            previous->next = current->next;
            current->next = previous->next->next;
            previous->next->next = current;
            
            recurse(current);            
        }
    }
public:
    ListNode* swapPairs(ListNode* head) {
        auto front = new ListNode(0, head);
        recurse(front);
        return front->next;
    }
};

error message

CodePudding user response:

UPD: I add some comments to illustrate the OP's correct solution:

        if(head!=nullptr and head->next!=nullptr 
           and head->next->next!=nullptr){
            // p->[c]->[x]->y; swap(c, x); y can be null
            auto previous = head, current = head->next;
            // p->c->x->y
            previous->next = current->next;
            // p->x->y; c->x->y
            current->next = previous->next->next;
            // c->y; p->x->y
            previous->next->next = current;
            // p->x->c->y 
            recurse(current);            
        }

original answer

  • Related