Learn-dsa..in 30 days!



























CC-13 : Implement pairwise swap of elements of LinkedList.

Description:

Given an input LinkedList, implement pairwise swap of its elements.

Test cases and expected outputs:

Input Parameters Expected outputs
Linked List:
1->2->3->4->
Linked List after pairwise swap:
2->1->4->3->

Pseudocode:

pairwiseSwap(firstNode):

If first==null, return first; (base case).
If first.nextNode==null, return first.
Set variable listAfterCurrentPair=first.nextNode.nextNode.
Swap first 2 nodes:
Set newFirst to firstnode.nextNode.
Set newFirst.nextNode to firstNode.
Set first.nextNode to return value of recursive call to pairwiseSwap(listAfterCurrentPair).
Return newFirst.

Code:

public LinkedListnode pairwiseSwap(LinkedListnode first){
	if (first==null) {return first;}
	if (first.nextNode==null) {return first;}
	LinkedListnode listAfterCurrentPair=first.nextNode.nextNode;
	LinkedListnode newFirst=first.nextNode;
	newFirst.nextNode=first;
	first.nextNode=pairwiseSwap(listAfterCurrentPair);
	return newFirst;
}

Click here to download and run code and test cases !