Search code examples
javasingly-linked-listinsertion

Unexpected null value after adding node to the end of linked list


This is the code to insert a node at the end of a LinkedList. I have first created a head node. Then enter the values in list. After this, I created an end node and tried to linked it with the last node of the created list while traversing at the end of the list. But I am getting the null value in between. Can somebody correct my mistake?

Expected O/P: 2 3 4

O/P getting: 2 3 4 0 5

import java.util.Scanner;
     
 public class SinglyLinkedList {
     SinglyLinkedList next,head,ptr;
     int v;
     void headcre()
     {
         head=new SinglyLinkedList();
         ptr=head;
     }
     void linkcre(int n)
     {
         Scanner sc=new Scanner(System.in);
         System.out.println("Enter your values to be added in the list");
         for(int i=0;i<n;i++)
         {
             ptr.v=sc.nextInt();
             ptr.next=new SinglyLinkedList();
             ptr=ptr.next;
         }
         ptr.next=null;
     }
    
     void insertend()
     {
         Scanner sc=new Scanner(System.in);
         System.out.println("Enter value to be inserted at end");
 
         
         SinglyLinkedList node=new SinglyLinkedList();   //Creating a node
         node.v=sc.nextInt(); //assigning value to node
         node.next=null;
 
         SinglyLinkedList tail=head;
         
         //loop to traverse at the end of list
         while(tail.next!=null)
         {   
             tail=tail.next;
         }
         
         //pointing the list to the newly created node
         tail.next=node;
         tail=tail.next;
         
        //Printing the list after inserting end node
         SinglyLinkedList ptr3=head;
         while(ptr3!=null)
         {
             System.out.print(ptr3.v+" ");
             ptr3=ptr3.next;
         }
         //System.out.println(); 
     }

     public static void main(String[] args) {
         Scanner sc=new Scanner(System.in);
         System.out.println("Enter number of values in list");
         int n=sc.nextInt();
         SinglyLinkedList obj=new SinglyLinkedList();
          
         //function to create head
         obj.headcre();
         
         //function to create list
         obj.linkcre(n);
         
         //function to insert node at the end
         obj.insertend();
     }
 }

Solution

  • Change the tail.next to tail.next.next as below,

     //loop to traverse at the end of list
        while(tail.next.next!=null)
        {   
            tail=tail.next;
        }
    

    You are inserting the end node to the next of the null node created by the linkcre method.