I am building a Linked list here.
public ListNode addNode(ListNode head, ListNode temp){
if(head == null){
head = temp;
} else{
ListNode curr = head;
while(curr.next != null){
curr = curr.next;
}
curr.next = temp;
}
return head;
}
I have to merge two Linkedlist here. For e.g. we assume head as 1->2->3->null, temp as 4->5->null, I need the output as 1->2->3->4->5->null
On the head list, we have to move to last node so that we can merge the temp list. To move the pointer to the last node of the head list, I am iterating till I get next element as null which means the curr list will have 3->null alone when the while loop exists. Then, I am adding the temp list as the next element of curr. So, I assume I get 3->4->5->null.
But, when I return head element, I am getting 1->2->3->4->5->null.
How this works> Both curr and head are pointing to same objects right? When we change curr, head should point to the same. How is this working?