My difficult to understand 4ms solution


  • -1

    Why am I always thinking more complex and time consuming solutions? I am disappointed by myself

    class Solution {

    public:
        ListNode* swapPairs(ListNode* head) {
            if(head == nullptr || head->next == nullptr) return head;
            ListNode* t0 = head;
            ListNode* t1 = head -> next;
            ListNode* prev = nullptr;
            head = head -> next;
            if(t1 != nullptr && t1 -> next != nullptr){
                t0 -> next = t1 ->next;
                t1 -> next = t0;
                ListNode* temp = t1;
                t1 = t0;
                t0 = temp;
                prev = t1;
                t1 = t1 -> next -> next;
                t0 = t0 -> next -> next;
            }
            while(t1 != nullptr && t1 -> next != nullptr){
                prev -> next = t1;
                t0 -> next = t1 -> next;
                t1 -> next = t0;
                ListNode* temp = t1;
                t1 = t0;
                t0 = temp;
                prev = t1;
                t1 = t1 -> next -> next;
                t0 = t0 -> next -> next;
                
            }
            if(t1 == nullptr) return head;
            else if(prev != nullptr){
                prev -> next = t1;
                t1 -> next = t0;
                t0 -> next = nullptr;
                return head;
            }
            else{
                t1 -> next = t0;
                t0 -> next = nullptr;
                return head;
            }
        }
    };

Log in to reply
 

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