I have to implement natural mergesort on a linked list (that's easy) but I cannot change the "next" attribute of the nodes, just interchange the values they have. I also cannot go backwards because the nodes don't have a "prev" attribute. (Linked lists don't have random access) And I can't create new nodes.
I just need some hints on how the merge function should be.
I understand that keeping the two sublists ordered until I have them merged is the key, but I can't find a way to do it.
This is the Node class. They save a generic Item and the address of the next node
private class Node {
Item item;
Node next;
public String toString() {
if (next == null) return "[" + item + "]" + "->" + "null";
return "[" + item + "]" + "->" + next.item + ", ";
}
}