【问题标题】:Not able to traverse all the element in linked list in java无法遍历java中链表中的所有元素
【发布时间】:2021-09-04 14:32:56
【问题描述】:

我在 java 中的简单链表程序下面运行,但我得到了一个元素。 我得到的输出
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();
    }
}

【问题讨论】:

    标签: java data-structures linked-list output singly-linked-list


    【解决方案1】:

    你需要遍历LinkedList,直到节点不是null。如果当前节点不是null,则打印节点的数据并继续前进。但是如果你检查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();
        }
    }
    

    【讨论】:

      【解决方案2】:

      您的 while 条件检查列表中的下一项。您列表中的最后一项不满足您的条件。 最后一项的下一项始终为空。

      改变条件

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-24
        • 1970-01-01
        • 1970-01-01
        • 2015-10-23
        • 1970-01-01
        • 2013-06-11
        相关资源
        最近更新 更多