'facing problem while adding to a linked list, two seemingly identical codes are giving very different results
i am here trying to add a node to a singlylinkedlist
SinglyLinkedListNode s = new SinglyLinkedListNode(data);
if(head == null){SinglyLinkedList a = new SinglyLinkedList();
a.head = s;
return a.head;}
else{
SinglyLinkedListNode a = head;
while(head.next != null){
head = head.next;}
head.next = s;
return a;
}
this one works but if i do this -
SinglyLinkedListNode s = new SinglyLinkedListNode(data);
if(head == null){SinglyLinkedList a = new SinglyLinkedList();
a.head = s;
return a.head;}
else{
SinglyLinkedListNode a = head;
while(head != null){
head = head.next;}
head = s;
return a;
}
some how the list now contains only one node
Solution 1:[1]
In your first code while loop terminates when head.next != null, after termination head will point to last node in the linked list and when you do head.next = s it will append new node to you existing list.
In your second code while loop terminates when head == null, after termination head will point to null. so now you are assigning head = s so head will point to newly created node and it is not appended to your original list.
Solution 2:[2]
It should be very simple to find out with debugging step by step, and I guess that is way to learn it... try out putting break point at while loop and next line (assigning value directly to head), and check values of variables (mostly F8 key for debugging)...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Devesh jha |
| Solution 2 | Subhash |
