CC-3 : Delete middle node of a SingleLinkedList.
Description:
If SingleLinkedList has odd count of nodes n, then node at position (n/2+1) should be deleted.If SingleLinkedList has even count of nodes n, then it has 2 middle nodes, in this case delete node at position (n/2+1).If SingleLinkedList has only one node, delete the node.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| 6 -> 11 -> 7 -> 4 -> 23 -> 9 | 6 -> 11 -> 7 -> 23 -> 9 |
| 36 -> 51 -> 27 -> 55 -> 44 -> 23 -> 33 | 36 -> 51 -> 27 -> 44 -> 23 -> 33 |
| 33 | null |
Pseudocode:
| Create 2 pointers and use these to navigate to the end of the SingleLinkedList using nextNode links:
CurrentNode : this pointer is updated to nextNode in each step (i.e it will iterate Node1->Node-2->Node3 and so on).
CurrentNode2xspeed: this pointer is updated to next to nextNode in each iteration (i.e it will iterate to Node1->Node3->Node5 and so on).
Both above pointers should be incremented in the same loop.
When CurrentNode2xspeed reaches end of the SingleLinkedList, at that time currentNode will be pointing to middle of SingleLinkedList. Now we can use currentNode pointer to delete the node at the middle of the SingleLinkedList.
|
| Handle following special cases in your code:
SingleLinkedList empty.
SingleLinkedList having only one node.
SingleLinkedList having even number of nodes.
SingleLinkedList having odd number of nodes.
|
Code:
public SingleLinkedList deleteMiddleNode(SingleLinkedList singleLinkedList) throws Exception{
if (singleLinkedList.getFirstNode()==null) { return null; }
SingleLinkedListNode currentNode=singleLinkedList.getFirstNode();
SingleLinkedListNode currentNode2xspeed=singleLinkedList.getFirstNode();
int numberOfNodesInList=1;
int idx=0;
while (currentNode2xspeed.getNextNode()!= null) {
if (currentNode2xspeed.getNextNode().getNextNode()!=null) {
currentNode2xspeed=currentNode2xspeed.getNextNode().getNextNode();
numberOfNodesInList=numberOfNodesInList+2;
}
else {
currentNode2xspeed=currentNode2xspeed.getNextNode();
numberOfNodesInList=numberOfNodesInList+1;
}
currentNode=currentNode.getNextNode();
idx++;
}
singleLinkedList.removeAtPos(idx);
return singleLinkedList;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |