Table of Contents [hide]
If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
This is one of popular interview question. In this post, we will see how to reverse linked list in pairs.

Java Linked List Interview Programs:
- How to reverse a linked list in java
- How to reverse a linked list in pairs in java
- How to find middle element of linked list in java
- How to detect a loop in linked list in java
- Find start node of loop in linkedlist
- How to find nth element from end of linked list
- How to check if linked list is palindrome in java
- Add two numbers represented by linked list in java
- Iterative
- Recursive
Iterative:
Logic for this would be:
Explanation:
Lets understand with the help of simple example:
Lets say linkedlist is 5-> 6 -> 7 -> 1
If you look closely, below steps are just reversing link to 6->5->7->1 in first iteration (Swapping node 6 and 5) and then advance to next pair (Node 7 and 1)
You must be wondering why we have put below code:
before swapping two nodes , we need to link nodes properly. When we are swapping 7 and 1 , link between 5->7 will be broken and we need to connect node 5 to node 1.
As per above code , temp will be null in first iteration(swapping node 6 and 5) but when current node is 7, temp will be 6, here we are linking nodes as below
6->5->1->7
Java program for this will be :
Run above program, you will get following output:
Recursive:
Output of this program will be same as above program.
Please go through java interview programs for more such programs.