简体   繁体   中英

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

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. 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

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

So, the program keeps on allocating memory space n->head->head->head->... and so on until it reaches its limit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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