【发布时间】:2019-07-01 22:32:00
【问题描述】:
我正在实现一个有序链表,我想知道在调用 insert 方法时处理重复记录的最有效方法是什么。是在操作之前搜索记录是否已经存在,还是在操作中评估记录是否已经存在并抛出异常更好?
方法#1
public void insert(int key){
if(isEmpty())
head = new Node(key);
else if(key < head.data){
/* Code to verify if they are equal */
/* ... */
/* ... */
Node new_node = new Node(key);
new_node.next = head;
head = new_node;
}else{
Node tmp = head;
while((head.nex != null) && (key > tmp.key)){
/* Code to verify if they are equal */
/* ... */
/* ... */
tmp = tmp.next;
}
/* Create node and change "pointers"*/
/* ... */
/* ... */
}
}
方法#2
public void insert(int key){
if(exists(key)){
/* Throw an exception */
}
/* Code for insert element */
/* ... */
/* ... */
}
【问题讨论】:
-
在同一迭代中检查显然更有效。
-
如果效率是目标,为什么要使用链表?
-
链表 API 通常允许重复条目。列表还对其性能做出了一些承诺。例如,向列表中插入一个值应该花费恒定时间,检查重复条目会将其增加到 O(n)。如果您必须保证条目是唯一的,您可能会考虑使用不同的数据结构,例如 set。
-
@LeffeBrune 感谢您的回复和建议,这对我很有用。其实这是大学作业。也感谢其他人。
-
搜索一次总比搜索两次更有效,你不觉得吗?
标签: java performance data-structures linked-list