# 24     Swap Nodes in Pairs

## 24. [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/description/)

## 1. Question

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.

## 2. Implementation

```java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode curNode = dummy;
        ListNode first = null, second = null;

        while (curNode.next != null && curNode.next.next != null) {
            first = curNode.next;
            second = curNode.next.next;
            first.next = second.next;
            second.next = curNode.next;
            curNode.next = second;
            curNode = first;
        }
        return dummy.next;
    }
}
```

## 3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)
