我有一个排序的双向链表,其中第一个和最后一个元素为空。这意味着当我插入值 a、b、c 时。结果应如下所示: {null, a, b, c, null}
空的排序双向链表应如下所示: {null, null} 其中第一个和最后一个元素始终为空。
问题是当我在排序的双向链表中插入数据时,数据没有正确排序,2个空值总是在列表的末尾。我怎样才能解决这个问题?
这是我当前的插入方法:
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++;
}
}
富国沪深
尚方宝剑之说
繁星点点滴滴
相关分类