Iterative Solution (Does Anyone Have a Recursive Soln?)


  • 0
    I
            if (!head || !head->next) return head;
            
            ListNode* prev = nullptr;
            ListNode* first = head;
            ListNode* second = head->next;
            
            while (first && second) {
                first->next = second->next;
                second->next = first;
                if (prev == nullptr){
                    head = second;   
                } else {
                    prev->next = second;
                }
                prev = first;
                first = first->next;
                if (first != nullptr) second = first->next;
            }
            return head;
        }```

  • 0
    S
    if head == None or head.next == None:
        return head
    temp = head.next
    head.next = self.swapPairs(head.next.next)
    temp.next = head
    return temp
    

Log in to reply
 

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