简体   繁体   English

单链接列表:如何添加标题

[英]Singly Linked Lists: How to add the head

I have an assignment to implement a singly linked list. 我有一个任务来实现一个单链表。 I am trying to figure out how to get the head but I end up getting stack overflow errors or null pointer errors. 我试图弄清楚如何获得头,但最终却遇到了堆栈溢出错误或空指针错误。 Could someone help me. 有人可以帮我吗。 I have displayed the relevant pieces of code: 我已经显示了相关的代码段:

public class Llist {

    private Object data;
    private Llist next;
    private Llist head = new Llist(null, null);

    public Llist(Object d) {
        this(d, null);
    }

    public Llist(Object d, Llist n) {
        data = d;
        next = n;
    }

I have a method to add a node, it will check whether or not there is a head, if there isnt then the new node is the head: 我有一个添加节点的方法,它将检查是否有头,如果没有,则新节点为头:

public static Llist add(Llist l, Object d) {
    Llist n = new Llist(d,l);
    if(l.head == null) {
        l.head = n;
    }
    return n;
}

Currently I get a stack overflow error... but if I remove the line of setting the head to null in the 2 当前我收到一个堆栈溢出错误...但是如果我在2中删除将head设置为null的行

Your linked list isn't setup properly at all. 您的链接列表设置不正确。 A linked list should only have a reference to the head node, and the head node should hold a reference to the next node. 链表仅应具有对头节点的引用,而头节点应具有对下一个节点的引用。 It should look more like: 它看起来应该更像:

public class Llist {

    private Object data;
    private Llist next;

    public Llist(Object d) {
        this(d, null);
    }

    public Llist(Object d, Llist n) {
        data = d;
        next = n;
    }

In which case you should always hold a copy of the head node, otherwise you lose the whole list, because your list and nodes are the same type in this implementation. 在这种情况下,您应始终持有头节点的副本,否则将丢失整个列表,因为在此实现中,列表和节点的类型相同。

A better implementation would have a separate Node class. 更好的实现将有一个单独的Node类。 Something like: 就像是:

public class Llist {
    private Node head;

    public Llist(Object o) {
        head = new Node(o);
    }

    public void add(Object o){
        curr = head;
        while(curr != null){
             curr = curr.next;
        }
        curr.next = new Node(o)
    }

public class Node{
    Object data;
    Node next;

    public Node(Object o){
        data = o;
        next = null;
    }
}

The reason for Stackoverflow error is you are stuck in a infinite recursion Stackoverflow错误的原因是您陷入了无限递归中

public static Llist add(Llist l, Object d) {
    Llist n = new Llist(d,l);

Here you create a object n which has head object of type Llist, the head object inturn has another head object of type Llist 在这里,您创建了一个对象n ,它的头部对象的类型为Llist,而头部对象的另一个对象是Llist类型的对象

So, the program keeps on allocating memory space n->head->head->head->... and so on until it reaches its limit 因此,程序会继续分配内存空间n->head->head->head->... ,依此类推,直到达到极限为止

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM