public class LinkedList {
static Node head;
static class Node{
int data;
Node next;
Node(int dat){
data = dat;
next = null;
}
}
public void add(int data){
Node node = new Node(data);
Node n = head;
while (n!= null){
n = n.next;
}
n = node;
}
public void print(){
Node n = head;
while(n!=null){
System.out.println(n.data);
n = n.next;
}
}
}
I realize that in the add() method I am assigning 'node' to an item that has the value null, however, the doubt is even is n.next becomes null its still a node right because 'next' is defined as a Node, so it should work right.
To add the new node at the end of the linked list, you need to take following steps:
head
to the new node and return from the functionnext
of the last node to the new node created in step 1.There are couple of problems in your code:
while
loop in the add()
method doesn't stops when the last node is reached. It only stops when n
itself becomes null
which means you cannot add the new node in the linked listYou need to change the condition in the while
loop from
n != null
to
n.next != null
to make sure that you are at the last node in the linked list after the loop ends and then to add the new node in the linked list, you need to point the next
of the last node to the new node
n.next = node;
Your add()
method should be written as:
public void add(int data) {
Node node = new Node(data);
if (head == null) {
head = node;
return;
}
Node n = head;
while (n.next != null){
n = n.next;
}
n.next = node;
}