将虚拟节点保持在链表中

时间:2015-10-22 02:35:45

标签: java linked-list dummy-variable

我希望在不删除/替换虚拟节点head的情况下将新节点添加到列表中,即head始终 null ,列表将启动来自head.next (head -> node -> node -> node) 。我在使用虚拟节点的语法时遇到了麻烦,我不确定我是否正确行事。请问smb请看一下?提前谢谢!

我在构造函数的这一行得到nullPointer

this.head.next = null;

CODE

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;
    }
}

1 个答案:

答案 0 :(得分:0)

我猜你误解了链表的概念。成员变量head指向链表的起始地址。它不能为空。 head.next应该指向第二个元素,而head本身指向第一个元素。此外,在向列表添加新节点时,您不必更改head的值,除非您插入的节点应该放在链表的开头。在这种情况下,您需要更新head以指向新节点。为了在链表的中间或末尾插入节点,这不是必需的。

进一步阅读:

  1. http://crunchify.com/how-to-implement-a-linkedlist-class-from-scratch-in-java/

  2. http://www.tutorialspoint.com/java/java_linkedlist_class.htm