-1

そのため、メソッドパラメーターを介して入力されたリストを操作しないように、別のリストを作成したいと思います。基本的には、ループが終了したときに「結果」が「p」と同じになるようにしたいのですが、何らかの理由でうまくいきません。

private static Node<Integer> multByScalarAndCarry(Node<Integer> p , int k, int c){
          int carry = c; //carry is taken from parameter
          Node<Integer> result = new Node<Integer>();
          Node<Integer> z = result; //head for the copy list
          Node<Integer> P = p; //pointer for the list being copied
          //copy p into result
          while(P.next!=null){
              z.item = P.item;
              z.next = new Node<Integer>();
              z = z.next;
              P = P.next;
          }
...
}

k と c は無視してください。これらは私の質問には関係ありません。私はこの方法を完成させることに非常に近づいており、これが私が必要とする最後の部分です. 助けてください!

編集 [解決策]: 将来この問題が発生する人のために、リストをコピーする別の方法を使用して考えてみました。

再帰的な解決策は次のとおりです。

private static Node<Integer> copyNode(Node<Integer> p){
       if(p == null) //if empty, return the same thing
           return p;
       Node<Integer> result = new Node<Integer>();
       result.item = p.item;// construct a node item copy of p's item
       result.next = copyNode(p.next); //attach list doing this for all nodes of p
       return result; //return the result.
}
4

1 に答える 1

1

z=z.next が問題です。現在のノードを、前の行でインスタンス化したノードに変更しています。

于 2013-10-22T19:33:47.000 に答える