簡體   English   中英

無法遍歷java中鏈表中的所有元素

[英]Not able to traverse all the element in linked list in java

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

您需要遍歷 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();
    }
}

您的 while 條件檢查列表中的下一項。 您在列表中的最后一項不滿足您的條件。 最后一項的下一項始終為空。

改變條件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM