我想在不删除/替换虚拟节点的情况下将新节点添加到列表中head
,即head
始终为null并且列表将从head.next
(head -> node -> node -> node)
. 我在使用虚拟节点的语法时遇到问题,我不确定我是否做得对。smb可以看看吗?提前致谢!
我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;
}
}