Learn-dsa..in 30 days!



























CC-6 : Swap adjacent nodes of SingleLinkedList.

Description:

Given an input SingleLinkedList, traverse the list 2 nodes at a time. Swap the current 2 nodes and then pick up the next 2 nodes and so on till end of the SingleLinkedList is reached.

Test cases and expected outputs:

Input Parameters Expected outputs
2->1->4->3->6->5->10 1->2->3->4->5->6->10
10->11->12->13->14->15 11->10->13->12->15->14

Pseudocode:

Traverse the input SingleLinkedList starting from its firstNode using a do-while loop till end of SingleLinkedList is reached:
Swap the currentnode and its nextNode.
Correct the linkages with nodes before current node and after nextNode.
Handle cases of odd number of nodes in SingleLinkedList , due to which last node is not part of pair of nodes.

Code:

public SingleLinkedList singleLinkListSwapNodes(SingleLinkedList singleLinkedList) throws Exception{
	if ((singleLinkedList.getFirstNode()== null)||(singleLinkedList.getSize()==1)) 
		{return singleLinkedList;}
	SingleLinkedListNode currentNode=singleLinkedList.getFirstNode();
	SingleLinkedListNode prevNode=null; 
	SingleLinkedListNode nextNode=null; 
	do {
		nextNode=currentNode.getNextNode();
		if (nextNode==null) {return singleLinkedList;}
		if (prevNode != null) {
			prevNode.setNextNode(nextNode);
		}
	    if (currentNode==singleLinkedList.getFirstNode()) 
	    	{singleLinkedList.setFirstNode(nextNode);}
		currentNode.setNextNode(nextNode.getNextNode());
		nextNode.setNextNode(currentNode);
		prevNode=currentNode;
		currentNode=currentNode.getNextNode();		
	} while(currentNode != null);
	return singleLinkedList;
}

Click here to download and run code and test cases !