Swap nodes in pairs O(1) space and O(n) time


  • 0
    A
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            if (!head || !head->next) return head;
            ListNode *prev = nullptr;
            auto current = head;
            auto next = current->next;
            while (next) {
                auto tmp = next->next;
                if (!prev) { head = next;}
                if (prev) prev->next = next;
                prev = next;
                prev->next = current;
                current->next = tmp;
                prev = current;
                current = current->next;
                if (current) next = current->next;
                else next = nullptr;
            }
            return head;
        }
    };

Log in to reply
 

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