【发布时间】:2021-01-20 19:37:19
【问题描述】:
我正在尝试为双向链表编写插入方法,当我将节点放入列表时,它按字母顺序插入。这个想法是我将使用 curnode 遍历列表,如果 newNode 在 curnode 之前,我将简单地将 newNode 放在 curnode 之前。到目前为止,我编写的代码可用于将 1 个节点插入到列表中,但我遇到了需要检查订单并在之前放置的第二部分的问题。我应该如何更改程序以使其正常工作?使用我现在只有 1 个元素(头部)的代码将被插入。
void insert(String x){
node curnode = head;
node newNode = new node(x);
//list is empty so insert as normal - [works fine]
if (head == null){
head = newNode;
head.prev = null;
head.next = null;
tail = newNode;
}
//Now insert node with respect to alphabetical order - [problem area]
else {
// while the list isn't empty
while (curnode != null){
// if newNode alphabetically comes before the curnode then place before
if (curnode.data.compareTo(newNode.data) > 0){
node temp = curnode.prev;
curnode.prev = newNode;
newNode.next = curnode;
newNode.prev = temp;
break;
}
}
}
}
【问题讨论】:
-
仅供参考: Java 命名约定规定类名应以大写字母开头,因此
node应为Node。
标签: java algorithm sorting doubly-linked-list