リンクされたリストをバッグの形で実装する必要があります。通常、バッグには取り外しがありませんが、この場合は必要です。
テスト クライアントを実行して remove を呼び出すと、最初の値を除いて、リンク リスト内のその項目のすべてのインスタンスが削除されます。
したがって、基本的に私の出力は次のようになります。
removed all 9s: 4 4 4 4 4 3 3 3 3 3 2 2 2 2 2 1 1 1 1 1 4 4 3 3 2 2 1 1
removed all 3s: 4 4 4 4 4 2 2 2 2 2 1 1 1 1 1 4 4 2 2 1 1
removed all 1s: 4 4 4 4 4 2 2 2 2 2 4 4 2 2
removed all 4s: 4 2 2 2 2 2 2 2
removed all 2s: 4
これが私のコードです:
public void remove (int item)
{
// TODO
Node previous = null;
Node current = first;
if (first == null) // list is empty do nothing
{
}
else if (first.item == item) // item occurs in first node
{
//previous = first;
first = first.next;
} // skip around first node
else
{
// find the node before item
for (Node p = first.next, q = first; p != null; q = p, p = q.next)
{
if (p.item == item)
{
q.next = p.next;
//p.next = q.next;
//return;
}
}
}
while (current != null)
{
if(current.item == item)
{
current = current.next;
if (previous == null)
previous = current;
else
previous.next = current;
}
else
{
previous = current;
current = current.next;
}
} //end while
//return;
}
テスト クライアント コードは次のとおりです。
b1.remove(9);
print ("removed all 9s", b1); // does nothing
b1.remove(3);
print ("removed all 3s", b1);
b1.remove(1);
print ("removed all 1s", b1);
b1.remove(4);
print ("removed all 4s", b1);
b1.remove(2);
print ("removed all 2s", b1); // should be empty
削除されたはずの4が残っている理由を誰かが理解するのを手伝ってくれますか?