ダミーノードを削除/置換せずにリストに新しいノードを追加したいhead
、つまりhead
、常にnullであり、リストはから始まりhead.next
(head -> node -> node -> node)
ます。ダミー ノードの構文に問題があり、正しく実行しているかどうかわかりません。ちょっと見てくれませんか?前もって感謝します!
nullPointer
コンストラクターのこの行で取得しています:
this.head.next = null;
コード
package SinglyLinkedList;
import java.util.*;
public class Tester {
public static void main(String[] args){
LinkedList<Integer> myList = new LinkedList<Integer>();
myList.insert(1);
myList.insert(2);
myList.insert(3);
myList.displayList();
}
}
クラスLink
package SinglyLinkedList;
import java.util.Iterator;
public class Node<T> {
public T data;
public Node<T> next;
public Node(T data){
this.data = data;
}
public void display(){
System.out.print(this.data + " ");
}
}
class LinkedList<T> implements Iterable<T>{
private Node<T> head;
private int size;
public LinkedList(){
this.head = null;
this.head.next = null;
this.size = 0;
}
public boolean isEmpty(){
return head == null;
}
public void displayList(){
if(head.next == null){
System.out.println("The list is empty");
}
else{
Node<T> current = head.next;
while(current != null){
current.display();
current = current.next;
}
}
}
public void insert(T data){
Node<T> newNode = new Node<T>(data);
if(head.next == null){
head.next = newNode;
}
else{
newNode.next = head.next;
head.next = newNode;
}
size++;
}
@Override
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return null;
}
}