---
# System prepended metadata

title: 'Swap Nodes in Pairs <img src="https://img.shields.io/badge/-medium-orange">'
tags: [data_structure_python]

---

---
tags: data_structure_python
---

# Swap Nodes in Pairs <img src="https://img.shields.io/badge/-medium-orange">

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

# Solution

```python=
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if head == None or head.next == None:
            return head
        else:
            # 1) Swap adjacents nodes.
            tmp = head.next
            head.next = head.next.next
            tmp.next = head
            head = tmp
            # 2) Attach nodes.
            head.next.next = self.swapPairs(head.next.next)
            return head
```
