Reputation: 77
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?
Upvotes: 2
Views: 68
Reputation: 1888
When calling a method in Java, the variables are copied, not referenced. This means that in your case, the variable head
inside the insert
method 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.
private Node insert(Node head, int data)
{
Node node = new Node(data);
if (head != null) {
node.nextLink = head;
}
head = node;
return head;
}
In this case your main method should look like:
// LinkedList 10->20->30
head = new Node(30);
head = insert(head, 20);
head = insert(head, 10);
// Add the new 4 head: 4->10->20->30
head = insert(head, 4);
// Traversing
traversingLinkedList(head);
Upvotes: 1
Reputation: 393771
head
is a local variable, so assigning values to it inside your insert(Node head, int data)
doesn't affect the Node
passed to the method.
If your insert
method is part of some LinkedList
class, that class should hold a reference to the head of the list, and insert
should assign to that reference. In that case you won't need to pass Node head
as argument to insert
.
The only way you can modify the list by using the passed Node
argument is if the method would change the nextLink
of that Node
.
Upvotes: 1