简体   繁体   English

无法遍历java中链表中的所有元素

[英]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.我在 java 中的简单链表程序下运行,但我得到了一个元素。 The output I'm getting我得到的输出
10 10
8 8
1 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();
    }
}

You need to traverse the LinkedList till the node is not null .您需要遍历 LinkedList 直到节点不为null If current node is not null , print the node's data and move ahead.如果当前节点不为null ,则打印节点的数据并继续。 But if you check curentNode.next != null you can print the data till second last node only.但是,如果您检查curentNode.next != null您只能将数据打印到倒数第二个节点。

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

Your while condition checks for next item in the list.您的 while 条件检查列表中的下一项。 Your last item in the list does not satisifies your condition.您在列表中的最后一项不满足您的条件。 Last item's next item is always null.最后一项的下一项始终为空。

change the condition改变条件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM