# 24. Swap Nodes in Pairs

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

Example:

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

Note:

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

# Solution

Approach 1: Swap every two nodes.

# Code (Python)

Approach 1:

# Code (C++)

Approach 1:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode dummyHead(0);
        dummyHead.next = head;
        ListNode *prev = &dummyHead;
        ListNode *curr = head;
        while (curr && curr->next)
        {
            ListNode *nextNext = curr->next->next;
            prev->next = curr->next;
            curr->next->next = curr;
            curr->next = nextNext;
            prev = curr;
            curr = curr->next;
        }
        return dummyHead.next;
    }
};