0

LinkedListのaddメソッドをオーバーロードして、新しいCustomerOrdersを注文番号(整数)の順に追加する必要があります。これが私がこれまでに持っているコードです。

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;
}

注文番号1から5で注文を入力すると、リストは1,5,4,3,2になります。私が欲しいのは、リストを1、2、3、4、5にすることです。誰かが私がどこで間違っていたかを指摘し、それを修正するためのいくつかのヒントを教えてもらえますか?

4

1 に答える 1

3

実際に必要なデータ構造はPriorityQueueだと思います。

コードのバグに関する限り、問題は現在i.add(order)、新しい要素を小さな要素のに挿入することですが、必要な順序を取得するには、大きな要素の前に挿入する必要があると確信しています。

于 2012-10-02T01:15:36.463 に答える