Learn-dsa..in 30 days!



























CC-4 : Rotate Linked list by n nodes.

Description:

Given a SingleLinkedList, write and test code that rotates an existing Single Linked List by n nodes. Note n can be greater than the count of nodes in the SingleLinkedList.

Test cases and expected outputs:

Input Parameters Expected outputs
93->16->66->11->77->43->23->9
Rotate by 1 place
16->66->11->77->43->23->9->93
16->66->11->77->43->23->9->93
Rotate by 3 places
77->43->23->9->93->16->66->11
77->43->23->9->93->16->66->11
Rotate by 8 places
77->43->23->9->93->16->66->11
77->43->23->9->93->16->66->11
Rotate by 12 places
93->16->66->11->77->43->23->9

Pseudocode:

The method receives following input parameters: singleLinkedList (SingleLinkedList), nodesToBeRotated (int).
Declare variable named oldFirstNode and set it to singleLinkedList.getFirstNode().
By iterating on the singleLinkedList nodes next links, Find the length of the singleLinkedList and set it in variable listlength and also find reference to last node of SingleLinkedList and set it in variable oldlastNode.
Do following modulo operation to find effective number of node movements to be done:
effectiveMoves = n % listlength
Declare variable named newFirstNode and set it to singleLinkedList.getFirstNode().
Declare variable named newLastNode and set it to null.
To rotate the singleLinkedList, Iterate through the singleLinkedList using a for loop, with loop variable incrementing from 1 to effectiveMoves-1 and execute following steps:
Set variable newLastNode to newFirstNode.
Set variable newFirstNode to newFirstNode.getNextNode().
When above loops completes, newFirstNode will point to the node that is reached by moving forward effectiveMode positions and newLastNode will point to 1 node previous to the newFirstNode.
Set oldLastNode.setNextNode to singleLinkedList.getFirstNode().
Set newLastNode.setNextNode to null.
Set singleLinkedList.setFirstNode to newFirstNode.
Return rotated singleLinkedList.

Code:

public SingleLinkedList singleLinkListRotateList(SingleLinkedList singleLinkedList, int nodesToBeRotated) throws Exception{
	SingleLinkedListNode oldLastNode=singleLinkedList.getFirstNode();
	int singleLinkedListNodeCount=1;
	while (oldLastNode.getNextNode() !=null) {
		oldLastNode=oldLastNode.getNextNode();
		singleLinkedListNodeCount++;
	}
	int effectiveNodesToBeMoved= nodesToBeRotated % singleLinkedListNodeCount;
	if (effectiveNodesToBeMoved<=0) { return singleLinkedList; }
	SingleLinkedListNode newFirstNode=singleLinkedList.getFirstNode();
	SingleLinkedListNode newLastNode=null;
	for (int i=1; i<=effectiveNodesToBeMoved; i++) {
		newLastNode=newFirstNode;
		newFirstNode=newFirstNode.getNextNode();
	}
	oldLastNode.setNextNode(singleLinkedList.getFirstNode());
	newLastNode.setNextNode(null);
	singleLinkedList.setFirstNode(newFirstNode);
	return singleLinkedList;
}
	

Click here to download and run code and test cases !