我有一个任务,我从头开始创建一个自定义的有序链接列表。我很高兴在作业中获得了近乎完美的分数,但我因为不允许重复而被计算在内。假设我再添加“A”,然后再添加“A”。它只打印一个“A”。有没有人对我如何实现这个有任何建议?我将展示我的添加方法。如果有人想要更多代码,请随时提出,我很乐意提供。
注意:作业已经完成,因此已经评分。
public boolean add(Comparable obj) {
// TODO: Implement this method (8 points)
//FOR REFERENCE - public OrderedListNode(Comparable item, OrderedListNode previous, OrderedListNode next) {
try {
OrderedListNode node; //create new OrderedListNode for comparison
for (node = head; node.next != tail; node = node.next) { //loop one node at a time until next node is tail
int compare = obj.compareTo(node.next.dataItem); //compare current object with next node
if (compare == 0) {
return false; // Nope
}
if (compare < 0) { //obj is less than next node, so insert previous next
break;
}
}
OrderedListNode newNode = new OrderedListNode(obj, node, node.next);
newNode.next.previous = newNode; //swapping nodes
node.next = newNode;
System.out.println("Added: " + obj); //display elements added
modCount++; //another modification
theSize++; //increment size by 1
} catch (ClassCastException e) { //give message to user
System.out.println(RED + "Caught Exception" + RESET_COLOR);
System.out.println("'" + obj +"'" + RED + " not added" + RESET_COLOR);
}
return true; //successful add
}
答案 0 :(得分:1)
更改
if (compare == 0) {
return false; // Nope
}
if (compare < 0) { //obj is less than next node, so insert previous next
break;
}
到
if (compare <= 0) { //obj is less than or equal next node, so insert previous next
break;
}
对我来说,如果它等于另一个项目,它会让你仍然插入该项目。