1

挿入コードは、最後の挿入まで完全に機能しているように見えますが、順番に追加するのではなく、リストの最後に配置します。

public void insert(Comparable item)
{
    if ( this.first == null || item.compareTo(this.first.data) <= 0)
    {
        addFirst(item); 
    }
    else if( item.compareTo(this.first.data) > 0 )
    {
        addLast(item);
    }
    else
    {
        Node oldFirst = this.first;
        this.first = this.first.next;

        insert(item);

        this.first = oldFirst;
    }
}

これは、それが生成する出力です...

6 Item(s) 

5
16
21
22
45
23

remove メソッドは、アイテムを削除した後にコンパイルを停止しますが、その理由がわかりません。

public Comparable remove(Comparable item)
{
    if( this.first == null )
    {
        return null;
    }

    Node oldFirst = this.first;

    if( this.first.next == null && this.first.data.equals(item) )
    {
        Comparable found = this.first.data;
        this.first = null;
        return found;
    }                

    this.first = this.first.next;

    if( this.first.data.equals(item) )
    {
        Comparable found = this.first.data;
        oldFirst.next = this.first.next;
        this.first = oldFirst;
        return found;
    }

    Comparable foundIt = remove(item);       

    return foundIt;
}

これは remove メソッドからの出力です....

at List.remove(List.java:164)
Removed: 21. List has: 4 Item(s) 
at List.remove(List.java:164)

16
at List.remove(List.java:164)
22
45
at TestRecursion.main(TestRecursion.java:87)
4

3 に答える 3

0

挿入メソッドは最後に 23 を追加します。

 item.compareTo(this.first.data) > 0 

23 は確かにあなたの最初の要素以上のものです。

于 2013-07-26T14:20:27.297 に答える
0

item が最初の要素よりも大きい場合、 addLast を呼び出すことに気付きました。これは、ソートされたリストを提供しません。

1、4、2、3 で挿入を呼び出すことを検討してください。出力はまさにその順序になります。1、4、2 3。

また、削除がクラッシュする理由について...

//what if its last item, and the data !.equals(item)?
if( this.first.next == null && this.first.data.equals(item) )
{
    Comparable found = this.first.data;
    this.first = null;
    return found;
}   
this.first = this.first.next;
//first could be null here if you are at end of list.
if( this.first.data.equals(item) )
{
    Comparable found = this.first.data;
    oldFirst.next = this.first.next;
    this.first = oldFirst;
    return found;
}

デバッガを使用することをお勧めします。早く片付けなきゃ。

于 2013-07-26T14:15:05.557 に答える