リンクリストの末尾に要素を挿入しようとしていますinsertAtEnd()
。コードをデバッグすると、挿入の最初にnode(0,null)
がデフォルトとして挿入されています。私はこれがリストを反復しながら問題を引き起こしていると思います。どのようにこれを修正するための任意の提案?LinkedList最後に挿入
package com.ds.azim;
public class Node {
//Node has 1. Data Element 2. Next pointer
public int data;
public Node next;
//empty constructor
public Node(){
//
}
public Node(int data){
this.data= data;
this.next = null;
}
public Node(int data, Node next){
this.data = data;
this.next = next;
}
}
//*************************************//
package com.ds.azim;
public class SingleLinkedList {
//Single Linked list has a head tail and has a length
public Node head;
public Node tail;
public int length;
//constructor
public SingleLinkedList(){
head = new Node();
length = 0;
}
public void insertAtFirst(int data){
head = new Node(data,head);
}
public void insertAtEnd(int data){
Node curr = head;
if(curr==null){
insertAtFirst(data);
}else{
while(curr.next!=null){
curr = curr.next;
}
curr.next = new Node(data,null);
}
}
public void show(){
Node curr = head;
while(curr.next!=null){
//do something
System.out.print(curr.data+",");
curr = curr.next;
}
}
public static void main(String[] args){
SingleLinkedList sll = new SingleLinkedList();
sll.insertAtFirst(12);
sll.insertAtFirst(123);
sll.insertAtFirst(890);
sll.insertAtEnd(234);
sll.show();
}
}
おそらく、リストの最後のノードを指しているはずです(現時点ではあなたのコードでは使用されていませんが)。最後に挿入するのはちょうど 'tail.next = new Node(data)'の問題でなければなりません。 – sprinter
これは、構造体が変更され、 "空"が正しく処理されたときに 'tail'を更新する必要があります。 –
@sprinter応答に感謝します。私は尾を宣言したが、決してそれを使用しなかった。ヘッドポインタを使ってこの作品を作るにはどうすればいいですか? –