-4

So I'm trying to create a simple list class that implements the addFIrst and addLast algorithm to be more specific like this:

public class Node {

    private int item;
    private Node link;

    public Node(int item, Node link)
    {
        this.item=item;
        this.link=link;
    }

    public int getItem()
    {
        return item;
    }

    public Node getLInk()
    {
        return link;
    }

    public void setItem(int item)
    {
        this.item=item;
    }

    public void setLink(Node link)
    {
        this.link=link;
    }
}

public class LIsta {

    private Node head;

    public LIsta()
    {
        head=null;
    }

    public void insertFirst(int item)
    {
        Node n=new Node(item, head);
        head=n;
    }

    public void insertLast(int item)
    {
        Node temp=head;
        while(temp!=null) temp=temp.getLInk();
        Node n=new Node(item, null);
        temp.setLink(n);
    }

    public void Print()
    {
        Node temp=head;
        while(temp!=null)
        {
            System.out.println(temp.getItem());
            temp=temp.getLInk();
        }
    }

}

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        LIsta list=new LIsta();
        list.insertFirst(5);
        list.insertFirst(3);
        list.insertFirst(2);
        list.insertLast(8);
        list.Print();
    }

}

However it gives me an error whenever I try to call the insertLast() method more specifically in the line: temp.setLink(n);

It says: Null pointer access. The variable temp can only be a null at this point. Any Ideas?

kryger
  • 12,906
  • 8
  • 44
  • 65
David Mathers
  • 163
  • 2
  • 7
  • 2
    What about the error message do you not understand? You loop `while(temp!=null)`, so once your loop is done `temp` can only be null – OH GOD SPIDERS Oct 24 '17 at 08:35

1 Answers1

1

You iterate over the links until temp becomes null, and at this point you can't do anything with the temp variable. You need to find the last link (i.e. the last non-null Node whose getLInk() is null).

public void insertLast(int item)
{
    if (head == null) {
        head = new Node(item, null);
    } else {
        Node temp=head;
        while(temp.getLInk() != null) temp=temp.getLInk();
        Node n=new Node(item, null);
        temp.setLink(n);
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768