Deepu Singh
Deepu Singh

Reputation: 23

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();
    }
}

Upvotes: 0

Views: 173

Answers (2)

Angellic Doll
Angellic Doll

Reputation: 43

Your while condition checks for next item in the list. Your last item in the list does not satisifies your condition. Last item's next item is always null.

change the condition

Upvotes: 0

GURU Shreyansh
GURU Shreyansh

Reputation: 909

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();
    }
}

Upvotes: 1

Related Questions