24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.
// Iteration
ListNode* swapPairs(ListNode* head) { // time: O(n); space: O(1)
    ListNode *dummy = new ListNode(-1);
    dummy->next = head;
    ListNode *pre = dummy, *cur = head, *nex = nullptr;
    while (cur && cur->next) {
        nex = cur->next;
        cur->next = nex->next;
        nex->next = cur;
        pre->next = nex;
        pre = cur;
        cur = cur->next;
    }
    ListNode *res = dummy->next;
    delete dummy;
    return res;
}

Last updated

Was this helpful?