C++ 4ms solution


  • 0
    D
    ListNode* swapPairs(ListNode* head) {
            
            if(head == NULL || head->next == NULL) return head;
            
            bool swap = true;
            ListNode * firstNode = head;
            ListNode * prev = head;
            
            while(firstNode->next){
                
                if(swap){
                    ListNode * secondNode = firstNode->next;
                    firstNode->next = secondNode->next;
                    secondNode->next = firstNode;
                    
                    if(prev == head) {
                        head = secondNode;
                        prev = secondNode;
                    } else prev->next = secondNode;
                }
     
                else{
                    prev = firstNode;
                    firstNode = firstNode->next;
                }
                swap = !swap; 
                
            }
            
            return head;
        }

Log in to reply
 

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