So, I have been studied about linked list and had created this insert method.
private void insert(Node head, int data)
{
Node node = new Node(data);
Node first = head;
if(first == null)
{
head = node;
}
else
{
node.nextLink = first;
head = node;
//System.out.println(node.data);
}
}
and this traverse method
public void traversingLinkedList(Node head)
{
Node current = head;
while(current != null)
{
int data = current.data;
System.out.println(data);
current = current.nextLink;
}
}
But it is not showing the node when I am inserting it. The node data shows when I uncomment the print line in method insert.
for example,
LinkedList present is 10 -> 20 -> 30
after using insert(head,4) I still get 10 -> 20 -> 30
though in the method insert when I uncheck the print method it is showing first node data as 4
but when traversing it is not showing!
Why?
When calling a method in Java, the variables are copied, not referenced. This means that in your case, the variable
headinside theinsertmethod is only local and its modifications will not be visible outside the method.Thus, since you are inserting elements at the front, the new head after the insertion is the node you have created (not the previous one) and you need to return it to update the next calls. Moreover, you could simplify the code of your insert method since you will always update the head value and the only conditional part is if there are more elements in the list or not.
In this case your main method should look like: