我想在列表中添加新节点,而不删除/替换虚拟节点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();
}
}
Class 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;
}
}
我想你误解了链表的概念。成员变量head
指向链表的起始地址。它不能为空。head.next
应该指向第二个元素,而head
本身指向第一个元素。此外,在向链表中添加新节点时,您不必更改head
的值,除非您插入的节点应该位于链表的开头。在这种情况下,您需要更新head
以指向新节点。对于在链表的中间或末尾插入节点,则不需要这样做。
进一步阅读:
- http://crunchify.com/how-to-implement-a-linkedlist-class-from-scratch-in-java/
- http://www.tutorialspoint.com/java/java_linkedlist_class.htm