Hello,
First off, i did try looking around the forum but i couldn't understand. Here's a few question which i need help with:
1) (adding node at head) i don't know how does the head will hold the reference to the next node, the code is like this:
//at node class, part of the code:
void setNext(Node next)
{
this.next = next;
}
//at linklist class part of the code:
void addNode(int item)
{
Node newNode = new Node(item,null);
newNode.setNext(head);
head = newNode;
System.out.println(" Node added into the list........");
}
How does the head hold the reference to the next node?
2) (Adding node at end of list) I read that to do so, you have an object tail which you keep track. And then you assign the the newNode to the pointer of tail and then assign pointer of tail to tail.
i tried:
//tail was initialized to null in the first place.
if (head == null){
head = newNode;
}
else{
tail.next= newNode;
tail = tail.next;
}
someone(sorry i forgot who) suggested this method in another post. But it comes out the error "Null pointer exception, null"
So my question is, what is wrong with the code above and how do I keep track of the tail?