So I was given this code, which to my knowledge I am not allowed to change:
public void insertionSort () {
if (head == tail) {
// empty list is sorted
return;
}
Node nextNode = head.next; // start inserting second node
while (nextNode != tail) {
// set insertNode to node to be inserted in this iteration
Node insertNode = nextNode;
// set nextNode to node to be inserted in next iteration
nextNode = nextNode.next;
// find position where insertNode has to be inserted
Node current = insertNode.prev;
while (current != null && insertNode.value.compareTo(current.value) < 0) {
current = current.prev;
}
// insert insertNode after current
insertNode.moveAfter(current);
}
}
I am not very familiar with linked lists but from what I can tell if the second while loop operates on the first iteration then this code will pass null into moveAfter() So far for moveAfter() I have:
/**
* Inserts this node after the specified node. If this and the specified node
* refer to the same node in the list, the list remains unchanged. If the
* specified node current is null, then this node is inserted at the head of
* the list.
*
* Precondition: this Node and the specified node are two nodes of this list
* this node and the specified node are not equal to the tail
*
* @param node - the node in this list after which this node is inserted
*/
public void moveAfter (Node node) {
if(this.prev == null && node.next == null){
throw new NoSuchElementException();
}
if(node.prev == null && node.next==null){
throw new NoSuchElementException();
}
if(this == tail){
throw new NoSuchElementException();
}
if(node == tail){
throw new NoSuchElementException();
}
this.prev.next = this.next;
this.next = node.next;
node.next = this;
this.prev = node;
}
}
If I am correct that insertionSort() passes null to moveAfter() how can I rectify this and reset “current” to it original value if i can not change insertionSort();
*Side note: Apologies if my question is hard to read or not asked correctly. I seem to have a knack at screwing them up on this website.
The comments before your
moveAfter()method state:Since
insertionSort()uses aheadvariable, I assume this is a member variable which you can also use inmoveAfter()to do as the specification states.