Untitled

mail@pastecode.io avatar
unknown
plain_text
8 months ago
815 B
2
Indexable
Never
/**
 * 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 {
public:
    ListNode* swapPairs(ListNode* head) {
        if(!head || !head->next) return head;
        ListNode* trav=head;
        ListNode* tmp=trav->next;
        ListNode* prev=nullptr;
        while(trav!=NULL && trav->next!=NULL){
            trav->next=tmp->next;
            tmp->next=trav;
            if(prev) prev->next=tmp;
            else head=tmp;

            prev=trav;
            trav=trav->next;
            if(trav) tmp=trav->next;
        }    
        return head;
    }
};
Leave a Comment