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?