-3

リンクリストからノードを削除しようとしています!リンクリストには、次のデータが保存されています。

aa 1 1 1 1
bb 2 2 2 2
cc 3 3 3 3

私はJavaコードを使用していますが、私のコードは

Node p=first;

for(Node c=first;c!=null;c=c.next){

    if(c.data.startsWith(key)){
       if(c.next==null){

       }
       else{
           p=c;
       }

       if(c==first){
           first=first.next;
       }
       else{
           p.next=c.next;
       }
    }
}

このコードはデータ、つまりcc 3 333のみを正しく削除するだけであるという問題が発生しています。削除したいデータを削除できるように、コードの問題点を確認したいと思います。前もって感謝します。

4

3 に答える 3

1

ループの最後の行としてこれが必要です。

p = c;

かどうかのテストも削除する必要がありますc.next == null。キーを見つけたときにノードを削除することは関係ありません。

ループ全体は次のようになります。

for(Node c = first, p = null; c != null; p = c, c = c.next){

    if (c.data.startsWith(key)) {
       if (p == null) {
           first = c.next;
       } else {
           p.next = c.next;
       }
       break;
    }
    p = c;
}
于 2012-12-30T14:59:12.373 に答える
0

次のようにしてみてください。

Node lastNode = null;

// Traverse all nodes in the list
for (Node node = first; node != null; node = node.next) {

    // Check for node to delete
    if (node.data.startsWith(key)) {
       if (lastNode != null) {
           // directly link last node with next node to remove node
           lastNode.next = node.next;
       } else {
           // if the node to delete is the first node, update first node
           first = node.next;
       }
       // remember last node
       lastNode = node;
    }
}
于 2012-12-30T15:29:40.930 に答える
0

次のコードは必要ありません。

  if(c==first){
       first=first.next;
   }
   else{
       p.next=c.next;
   }

ループはすでに次のノードに移動しています。このコードは、他のすべてのノードをスキップするだけです。おそらくそれが鍵を見つけられない理由です。

于 2012-12-30T14:59:28.457 に答える