Share c++ code ,----------------


  • 0
    L
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            ListNode *curr = head;
            if(head==nullptr || head->next==nullptr) return head;
            ListNode *prev = curr;
            curr = curr->next->next;
    
            head = prev->next;
            prev->next->next = prev;
            prev->next = curr;
    
            while(curr){
                if(curr->next){
                    ListNode *tmp = curr;
                    curr = curr->next->next;
    
                    prev->next = tmp->next;
                    tmp->next->next = tmp;
                    tmp->next = curr;
    
                    prev = tmp;
                }else{
                    break;
                }
            }
            return head;
        }
    };

Log in to reply
 

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