user2916886 user2916886 - 3 months ago 8
Java Question

error in inserting node at the end of linked list in java

I wrote this code to insert a node at the end of the

linkedlist
but I am getting only the 1st element when I am printing the list:

public class LinkedList {

public class Link{

private int data;
private Link next;

public Link(int data,Link next){
this.data = data;
this.next = next;
}

public void printLink(){

System.out.print(data);
}

}

private Link head;

public LinkedList(){
head = null;
}

public void insertNode_end(int data1){

Link node = new Link(data1,null);

if(head == null){

node.next = head;
head = node;
}

else{
Link ptr = head;
while(ptr != null){
ptr = ptr.next;
}

node.next = null;
ptr = node;

}
}

public void printList(){
Link curr_node = head;
while(curr_node != null){
curr_node.printLink();
curr_node = curr_node.next;
}
}

public static void main(String args[]){

LinkedList obj = new LinkedList();

obj.insertNode_end(1);
obj.insertNode_end(2);
obj.insertNode_end(3);
obj.insertNode_end(4);
obj.insertNode_end(5);

obj.printList();
}

}


I only see
1
getting printed. I also tried to do
ptr.next = node
but then it throws
null pointer exception
.

What is the mistake I am making here?

Answer

Let's take a closer look at the part when head is not null.

Link ptr = head;
while(ptr != null){
    ptr = ptr.next;
}

When this loop terminates ptr will be null. Probably not what you want it to be (I presume you want it to be the last element in the list). You probably want to change it to:

Link ptr = head;
while(ptr.next != null){
    ptr = ptr.next;
}

Note that it won't cause NPE because we know head is not null. On to the next part.

node.next = null;
ptr = node;

Now node.next is ok (also unnecessary since you initialized it to null in the constructor), but what is the next instruction supposed to do? It only changes the local variable. You probably meant:

ptr.next = node;