[英]How do I overload LinkedList's add method?
I have to overload LinkedList's add method so that it add new CustomerOrders in order by their Order Number(an integer). 我必须重载LinkedList的add方法,以便它按其Order Number(整数)顺序添加新的CustomerOrders。 Here is the code I have so far. 这是我到目前为止的代码。
public boolean add(CustomerOrder order)
{
ListIterator<CustomerOrder> i = this.listIterator();
if(!(i.hasNext())) //there are no orders in the list
{
i.add(order);
return true;
}
while(i.hasNext())
{
int compare = order.compareTo(i.next(), 1);//compareTo returns 0 if the orders have the same order number, 1 if order greater order num, -1 if order has lower order num
if(compare == 0) //can't add the order if another order has the same order num
{
return false;
}
else
{
if(compare == 1) //order is greater than i.next()
{
i.add(order); //my guess is that the problem is here
return true;
}
}
}
return false;
}
When I enter orders with order numbers 1 through 5 the list is 1,5,4,3,2. 当我输入订单编号为1到5的订单时,列表为1,5,4,3,2。 What I want is for the list to be 1,2,3,4,5. 我想要的列表是1,2,3,4,5。 Can anyone point out where I went wrong and give me some tips to fix it? 谁能指出我出了问题的地方,并给我一些解决办法?
I think the data structure that you actually want is a PriorityQueue . 我认为您实际需要的数据结构是PriorityQueue 。
As far as the bug in your code goes, I'm pretty sure that the problem is that currently i.add(order)
will insert the new element after a smaller element, whereas to get the order you want you would need to insert it before a larger element. 就代码中的错误而言,我很确定问题是当前i.add(order)
将在一个较小的元素之后插入新元素,而要获得所需的顺序,则需要将其插入在 更大的元素之前 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.