1. Introduction

Pairwise swapping of nodes in a linked list refers to swapping the data of every two adjacent nodes. This process doesn’t involve any node deletion or new node creation. It only involves changing node values. In this blog post, we will implement a Java program to perform pairwise swap of a linked list.

2. Program Steps

1. Define a Node class to represent each element of the linked list.

2. Implement a LinkedList class to manage the list operations.

3. Within the LinkedList class, add a method named pairwiseSwap().

– Traverse the list and swap data of adjacent nodes.

4. Test the functionality with a driver method.

3. Code Program

Output:

Original List:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL

List after pairwise swap:
2 -> 1 -> 4 -> 3 -> 6 -> 5 -> NULL

4. Step By Step Explanation

1. The Node class represents an individual element of the linked list. Each node has data and a reference to the next node, next.

2. The LinkedList class provides basic linked list operations. We use the append method to add elements to the end of the list.

3. The pairwiseSwap method swaps the data of two adjacent nodes by:

– Traversing the list while ensuring the current and the next node are not null.

– Swapping the data values of these two nodes.

– Skipping the next node and moving on to the one after that.

4. In the LinkedListDemo class, we demonstrate this functionality by creating a linked list with numbers 1 to 6 and then performing pairwise swap.