> For the complete documentation index, see [llms.txt](https://mayanktyagi3111.gitbook.io/interview-prep/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mayanktyagi3111.gitbook.io/interview-prep/linked-list/swap-nodes-in-pairs.md).

# 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.
```

```java
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode prev = null, current = head;
        int count = 1;
        while (current != null) {
            if (count == 2) {
                ListNode next = current.next;
                if (prev == null) {
                    current.next = head;
                    head.next = next;
                    prev = head;
                    head = current;
                } else {
                    current.next = prev.next;
                    prev.next.next = next;
                    prev.next = current;
                    prev = current.next;
                }
                current = next;
                count = 1;
                continue;
            }
            current = current.next;
            count++;
        }
        return head;
    }
}
```
