### LeetCode - Swap Nodes in Pairs Solution - The Coding Shala

Home >> LeetCode >> Swap Nodes in Pairs

## LeetCode - Swap Nodes in Pairs Solution

In this post, you will learn how to solve LeetCode's Swap Nodes in Pairs problem with Java Solution. We will solve this problem using recursion and iteration.

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.

## Swap Nodes in Pairs Java Solution

Approach 1:
Iterative Solution.
Java Program:

```/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
//check for null or 1 node
//prev node need to link after swap so take prev
ListNode prev = null;
//while both the node are not null
while(curr1 != null && curr2 != null){
if(prev != null ) prev.next = curr2;
//swap
curr1.next = curr2.next;
curr2.next = curr1;
//change prev
prev = curr1;
//change curr1 and curr2
curr1 = curr1.next;
if(curr1 != null) curr2 = curr1.next;
}
return ans;
}
}
```
Approach 2:
Using Recursion.
Java Program:

```/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {

return second;
}
}
```

Other Posts You May Like