Search code examples
javadata-structureslinked-listsingly-linked-list

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

  • 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.