私は Java のビルトイン Linked List クラスを使用しないプログラムに取り組んでいます。私はゼロからそれを構築しています。Node をリンク リストの特定の位置に挿入するメソッドを作成する以外は、すべて成功しています。
特定のノードを「現在の」ノードとして設定するメソッドがあります。したがって、たとえば、次のようなリンク リストがあります:ネコ-->イヌ-->作る-->良い-->ペットで、"現在" は 2 です。つまり、「現在の」ノードは「犬」です。
ここから、「現在」の位置に新しいノードを挿入したいとしましょう。その情報フィールドはとです。正しく行われた場合、最終的にリンクされたリストは次のようになります。「and」は位置 2 の「dogs」を置き換えます。
ここに私の問題があります: 私の方法は新しいノードを位置 2 に挿入するように機能しますが、新しく作成されたノードを既存のノードにリンクすると何か問題が発生します。新しいノードをリストに挿入するだけでなく、「犬」の前に情報のないノードを挿入しています。私のコードを現在実行すると、出力は次のようになります。
問題がコードの (if current != null) 部分にあることは 99.9% 確信していますが、それを修正する方法がわかりません。
実際に追加したいノードに加えて、空白のノードを挿入する理由について何か考えはありますか?
public void insert () {
System.out.println("Please enter the text you wish to insert, or type \"end\" if you are done inserting.");
String theString;
theString = console.nextLine();
while (!theString.equals("end")){
newNode = new Node ();
newNode.info = theString;
newNode.next = null;
if (first == null){
first = newNode;
last = newNode;
} else if (current != null){
Node p = new Node (current.info, current.next);
current.info = newNode.info;
current.next = p;
}
else {
last.next = newNode;
last = newNode;
}
System.out.println("Please enter the text you wish to insert, or type \"end\" if you are done inserting.");
theString = console.nextLine();
}
}
編集
プログラム全体はかなり長いですが、ここにあるのは「setLine」メソッドで、ユーザーがノードを挿入したい位置に現在の値を設定します。ユーザープロンプトを介して取得されるパラメーター「int line」を取ります。
public Node setLine(int line) {
int index = 0;
current = first;
while (index < line) {
previous = current;
current = current.next;
index++;
}
return current;
}