I'm trying to make my Put method insert keys in order. Currently it seems to only insert in an unsorted order. How do I make it insert nodes into the correct position while maintaining the list.
public void put(Key key, Value val) {
if (key == null) throw new IllegalArgumentException("first argument to put() is null");
if (val == null) {
delete(key);
return;
}
Node x = first;
while (x != null && key.compareTo(x.key) <= 0) {
if (key.equals(x.key)) {
x.val = val;
return;
}
else {
x = x.next;
}
}
x = first;
Node newNode = new Node(key,val,x);
if (first==null || key.compareTo(x.key)>=0) {
newNode.next = first;
first = newNode;
}
else {
while(x.next != null && key.compareTo(x.next.key)<=0) {
x = x.next;
}
newNode.next = x.next;
x.next = newNode;
}
n++;
}
I am inserting each of these strings as keys in reverse order ("ant", "bee", "cat", "dog", "emu", "fox", "gem", "hat", "ice", "jar") and afterwards checking if the list is sorted. With my current implementation the list remains in reverse order and does not get sorted.