## Algorithm

Problem Name: 24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Example 1:

```Input: head = [1,2,3,4]
Output: [2,1,4,3]
```

Example 2:

```Input: head = []
Output: []
```

Example 3:

```Input: head = 
Output: 
```

Constraints:

• The number of nodes in the list is in the range `[0, 100]`.
• `0 <= Node.val <= 100`

## Code Examples

### #1 Code Example with C Programming

```Code - C Programming```

``````
struct ListNode* swapPairs(struct ListNode* head) {
struct ListNode *a, *b, *c;

if (a && a->next) {
b = a->next;
c = b->next;
b->next = a;
a->next = swapPairs(c);
return b;
}

return a;
}

``````
Copy The Code &

Input

cmd

Output

cmd
[2,1,4,3

### #2 Code Example with C++ Programming

```Code - C++ Programming```

``````
class Solution {
public:
ListNode res(0);
while (one && two) {
one->next = two->next;
two->next = one;
pre->next = two;
pre = one;
one = one->next;
if (one) two = one->next;
}
return res.next;
}
};
``````
Copy The Code &

Input

cmd

Output

cmd
[]

### #3 Code Example with Java Programming

```Code - Java Programming```

``````
class Solution {
ListNode prev = null;
while (curr != null && curr.next != null) {
ListNode nextNode = curr.next;
}
curr.next = nextNode.next;
nextNode.next = curr;
if (prev != null) {
prev.next = nextNode;
}
prev = curr;
curr = curr.next;
}
}
}
``````
Copy The Code &

Input

cmd

Output

cmd


### #4 Code Example with Javascript Programming

```Code - Javascript Programming```

``````
const swapPairs = function(node) {

while (node !== null) {
if (node.next !== null) {
let one = node;
let two = node.next;
let three = node.next.next;
cur.next = two;
two.next = one;
one.next = three;
cur = cur.next.next;
node = three;
} else {
cur.next = node;
break;
}
}

};

``````
Copy The Code &

Input

cmd

Output

cmd
[]

### #5 Code Example with Python Programming

```Code - Python Programming```

``````
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
second.next = self.swapPairs(first.next)
first.next = second
return first
``````
Copy The Code &

Input

cmd

Output

cmd
[2,1,4,3]

### #6 Code Example with C# Programming

```Code - C# Programming```

``````
namespace LeetCode
{
public class _024_SwapNodesInPairs
{
{

while (p.next != null && p.next.next != null)
{
q = p.next;
p.next = q.next;
q.next = p.next.next;
p.next.next = q;

p = q;
}

}
}
}
``````
Copy The Code &

Input

cmd