Skip to content
Advertisement

Not able to traverse all the element in linked list in java

I’m running below simple linked list program in java, but I’m getting one element short. The output I’m getting
10
8
1

public class SinglyLinkedList {
    ListNode head;

    private static class ListNode {
        int data;
        ListNode next;
        
        public ListNode(int data) {
            this.data=data;
            this.next = null;
        }
    }
    
    public void display() {
        ListNode curentNode = head;
        while (curentNode.next != null) {
            System.out.println(curentNode.data);
            curentNode = curentNode.next;
        }
    }

    public static void main(String[] args) {
        SinglyLinkedList sll = new SinglyLinkedList();
        sll.head =  new ListNode(10);
        ListNode second = new ListNode(8);
        ListNode third = new ListNode(1);
        ListNode fourth = new ListNode(10);
        sll.head.next = second;
        second.next = third;
        third.next = fourth;
        sll.display();
    }
}

Advertisement

Answer

You need to traverse the LinkedList till the node is not null. If current node is not null, print the node’s data and move ahead. But if you check curentNode.next != null you can print the data till second last node only.

public class SinglyLinkedList
{
    ListNode head;
    private static class ListNode
    {
        int data;
        ListNode next;
        public ListNode(int data)
        {
            this.data=data;
            this.next = null;
        }
    }
    public void display()
    {
        ListNode curentNode = head;
        while (curentNode != null) <------// Modified //
        {
            System.out.println(curentNode.data);
            curentNode = curentNode.next;
        }
    }

    public static void main(String[] args)
    {
        SinglyLinkedList sll = new SinglyLinkedList();
        sll.head =  new ListNode(10);
        ListNode second = new ListNode(8);
        ListNode third = new ListNode(1);
        ListNode fourth = new ListNode(10);
        sll.head.next = second;
        second.next = third;
        third.next = fourth;
        sll.display();
    }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement