Home > Net >  Linked List code number of output does not match the number of input
Linked List code number of output does not match the number of input

Time:10-06

In this java code as I input 4 integer type numbers in linked list it shows only first 3 as output so can you guide why is that. I when give only 1 value in linked list it doesn't appear when I give 2 values it shows the first one as output only.

here only output show 4, 34, and 5 but not 50 I don't understand what wrong with code?

enter code here
import java.lang.*;
public class Main{
    Node head;
    static class Node{
        int data;
        Node next;
        public Node(int d){
            data=d;
            next=null;
        }

    }


    public void insertFirst(int data)
    {
        Node n=new Node(data);
        n.next=head;
        head=n;

    }
    public void insertLast(int data){
        Node n=new Node(data);
        if(head==null) {
            head = n;

        }        else{
            Node t=head;
            while(t.next!=null)
            {   t=t.next;}
               t.next=n;
        }
      }
    public void display(){
            Node n=head;
            if(n==null)
                System.out.println("empty");
            else
            {
                while(n.next!=null)
                {
                    System.out.print(n.data " ");
                    n=n.next;
                }
            }
        }
       public static void main(String [] args){
        Main m=new Main();
       m.insertFirst(34);
           m.insertFirst(4);
       m.insertLast(5);
           m.insertLast(50);
        m.display();
       }
}

CodePudding user response:

When you reach the last node, node.next == null, you don't print it.

You need to change the condition in your display() method.

CodePudding user response:

Change while(n.next!=null) to while(n != null). The last node has n.next == null, but you should still print it.

  • Related