插入有序链表 - Java ADT
您好,这是我用于插入项目的代码...我被告知在列表开头插入时失败,但不明白为什么或如何修复它。
public void put(K key, V value){
OrderedLinkedListEntry <K,V> item = new OrderedLinkedListEntry (key, value);
OrderedLinkedListEntry <K,V> current = head;
OrderedLinkedListEntry <K,V> previous = null;
if(current == null){
head = item;
numItems ++;
return;
}
while(current != null){
int result = key.compareTo(current.getKey());
if(result == 0){
current.setValue(value);
return;
}else if (result < 0){
item.setNext(current);
if (previous != null){
previous.setNext(item);
}
numItems ++;
return;
}
previous = current;
current = current.getNext();
}
Hi this is my code for inserting an item...i was told it failed when inserting at the beginning of the list but don't understand why or how to fix it.
public void put(K key, V value){
OrderedLinkedListEntry <K,V> item = new OrderedLinkedListEntry (key, value);
OrderedLinkedListEntry <K,V> current = head;
OrderedLinkedListEntry <K,V> previous = null;
if(current == null){
head = item;
numItems ++;
return;
}
while(current != null){
int result = key.compareTo(current.getKey());
if(result == 0){
current.setValue(value);
return;
}else if (result < 0){
item.setNext(current);
if (previous != null){
previous.setNext(item);
}
numItems ++;
return;
}
previous = current;
current = current.getNext();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的解决方案中,当要插入的键小于头项中的键时,
previous
为 null。为新键小于头部键的特殊情况:
您还需要处理键大于最后一项中的键的情况(
结果> 0
案件)。In your solution,
previous
is null when the key to insert is less than the key in the head item.Make a special case for the new key being less than the key in the head:
You also need to handle the case in which the key is larger than the one in the last item (the
result > 0
case).