0

リンクされたリストをバッグの形で実装する必要があります。通常、バッグには取り外しがありませんが、この場合は必要です。

テスト クライアントを実行して 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が残っている理由を誰かが理解するのを手伝ってくれますか?

4

1 に答える 1

0

だから問題はラインにあります

if (previous == null){previous = current;}

最初の 3 つのアイテムは 4です。remove
(4) での手順は
first = first.next次のとおりです。 if ステートメントが true になる場合、previous も 2 番目の 4 を指します。
if(current.item == item) current = current.next
previous = current

さらに while ループでは、previous が null ではなく、current を previous.next に割り当てています。したがって、2 番目の 4 をスキップしたことはありません。

UPDATEhead他のノードが続くダミーノードを指すノードがあるとします。

remove(item)
{
    previous = head;
    current = head.next;
    while(current!=null)
    {
        if(current.item == item)
        {
            previous.next = current.next;
            current = current.next;
        }
        else
        {
            previous = current;
            current = current.next;
        }
    }
}
于 2013-07-01T19:16:37.820 に答える