24. Swap Nodes in Pairs (Easy)

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

For example,

Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Solution 1: iterative (Linked List)

ListNode* swapPairs(ListNode* head) {
    if (!head || !head->next) return head;
    ListNode* res = head->next, *prev = NULL;
    while (head && head->next) {
        //cout << head->val << " " << head->next->val << endl;
        ListNode* tmp = head->next->next;
        head->next->next = head;
        if (prev) prev->next = head->next;
        head->next = tmp;
        prev = head;
        head = head->next;
    }
    return res;
}

Solution 2: recursive

ListNode* swapPairs(ListNode* head) {
    if (!head || !head->next) return head;
    ListNode* t = head->next;
    head->next = swapPairs(t->next);
    t->next = head;
    return t;
}

results matching ""

    No results matching ""