簡體   English   中英

在LinkedList Java中打印第一個元素

[英]Printing the first element in LinkedList java

在給定的代碼下,一切工作正常,但顯示屏不會顯示最先插入的元素

 public void display()
    {
    Link pcurrent = pfirst;
    while(pcurrent.next!= null)
    {
      System.out.println(pcurrent);
      pcurrent = pcurrent.next;

    }
    }

依次插入元素: 100, 200, 300, 400 >輸出為:

//nothing in first turn 
200 
300, 200 (in second iteration)
400, 300, 200 in last iteration

我該如何改變?

我想要的是:

 100
  200, 100
  300, 200, 100
  400, 300, 200, 100

從您的代碼看來,您似乎有意要跳過打印pfirst 如果是這樣,請嘗試以下操作:

public void display()
{
    Link pcurrent = pfirst.next;
    while(pcurrent!= null)
    {
        System.out.println(pcurrent);
        pcurrent = pcurrent.next;
    }
}

在這里,我更改了在循環之前初始化pcurrent方式,更改了循環條件,並更改了循環體內事件的順序。

最好將它作為for循環來完成:

for (Link pcurrent = pfirst.next; pcurrent != null; pcurrent = pcurrent.next) {
    System.out.println(pcurrent);
}

如果您還想打印pfirst (聽起來像您實際想要執行的操作),則只需保留當前的pcurrent初始化,然后再進行其他更改即可。

我假設您將元素插入列表的前面。 在while循環中交換您的語句。

void print(list *head)
{
    list *pcurrent = head;
    while(head != NULL)
    {
      System.out.println(pcurrent);
      pcurrent = pcurrent.next;
    }
}

使用代碼,您首先要前進指針,然后嘗試打印該值。 只需在while循環中交換語句。 如果要打印整個列表,還應該更改while循環的條件。

  public void display() {
        Link pcurrent = pfirst;
        while(pcurrent!= null) {
                System.out.println(pcurrent);
                pcurrent = pcurrent.next;
         }
   }

暫無
暫無

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

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