I have a sorted doubly linked list in which the first and last elements are null. This means when I insert the values a, b, c. The result should look as follows: {null, a, b, c, null}
The empty sorted doubly linked list should look like this: {null, null} in which the first and last elements are always are null.
The problem is that when I insert data in the sorted doubly linked list, the data is not sorted correctly and the 2 null values are always at the end of the list. How can I fix this?
Here is my current insert method:
public void addElement(String element) {
// new node which will be inserted in the list
Node newNode = new Node();
newNode.data = element;
// if the list is empty
if (size == 0) {
last = newNode;
newNode.next = first;
first = newNode;
size++;
} else {
Node current = first;
// if the element should be at the beginning of the list
if (current.data.compareTo(element) > 0) {
newNode.next = current;
newNode.previous = null;
current.previous = newNode;
first = newNode;
} else {
while (current != null) {
if (current.data.compareTo(element) <= 0) {
if (current.next == null) {
newNode.next = current.next;
newNode.previous = current;
current.next = newNode;
break;
}
newNode.next = current.next;
newNode.previous = current;
current.next.previous = newNode;
current.next = newNode;
break;
} else {
current = current.next;
}
}
}
size++;
}
}
Nodeclass implementation,firstlastinitialization, and actual output that you are getting. Take a look at this stackoverflow.com/help/mcve