【问题标题】:Keeping the dummy nodes in linked list将虚拟节点保存在链表中
【发布时间】:2015-10-22 02:35:44
【问题描述】:

我想在列表中添加新节点而不删除/替换虚拟节点 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;
    }
}

【问题讨论】:

    标签: java linked-list dummy-variable


    【解决方案1】:

    我猜你误解了链表的概念。成员变量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

    【讨论】:

    • 但是 head 仍然是一个虚拟节点吗? @裂纹
    • @John 看,根据基础,head 甚至不是节点。相反,它是一个指向链表起始节点的对象引用变量。它所拥有的只是所需起始节点的地址。我建议在使用 Java 中的 Collections API 之前正确阅读这些概念并尝试从头开始实现链表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    相关资源
    最近更新 更多