循环打印出来 - java

use*_*642 0 java while-loop

我试图打印出链表中的所有元素.但是,我无法打印出完整的项目清单.

public void display()
    {
            int count =0;
            if (head == null)
            {
                    System.out.println("List is empty");
            }
            else {
                    ListNode temp = head;
                    while (temp.getNext() != null)
                    {
                            System.out.println(temp.getElement() +" ");
                            count ++;
                            temp = temp.getNext();

                    }
            System.out.println("Total element: "+count);
            }
    }
Run Code Online (Sandbox Code Playgroud)

//使用的方法

public ListNode getNext()
    {
            return this.next;
    }

    /*get the element of Listnode*/

    public int getElement()
    {
            return this.element;
    }
Run Code Online (Sandbox Code Playgroud)

请告知哪部分是错误的.

Pet*_*ser 5

你省略了链表的最后一个元素(因为它没有下一个元素).该while情况应该是这样的:

  while (temp != null)
Run Code Online (Sandbox Code Playgroud)