简体   繁体   English

在LinkedList Java中打印第一个元素

[英]Printing the first element in LinkedList java

Everything is working fine int he given code, except that the display does not print the first most inserted element 在给定的代码下,一切工作正常,但显示屏不会显示最先插入的元素

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

    }
    }

with elements inserted in order : 100, 200, 300, 400 -> It outputs them as: 依次插入元素: 100, 200, 300, 400 >输出为:

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

How do I change this? 我该如何改变?

What I want is this: 我想要的是:

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

From your code, it seems that you intentionally want to skip printing pfirst . 从您的代码看来,您似乎有意要跳过打印pfirst If so, try this: 如果是这样,请尝试以下操作:

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

Here, I've changed how pcurrent is initialized before the loop, changed the loop condition, and changed the order of events inside the loop body. 在这里,我更改了在循环之前初始化pcurrent方式,更改了循环条件,并更改了循环体内事件的顺序。

This should perhaps be better done as a for loop: 最好将它作为for循环来完成:

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

If you also want to print pfirst (which sounds like what you actually want to do), then just keep the initialization of pcurrent as you currently have it and still make the other changes. 如果您还想打印pfirst (听起来像您实际想要执行的操作),则只需保留当前的pcurrent初始化,然后再进行其他更改即可。

I assume you are inserting the element in the front of the list. 我假设您将元素插入列表的前面。 Swap your statement in the while loop. 在while循环中交换您的语句。

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

With your code, you first advancing the pointer then trying to print the value. 使用代码,您首先要前进指针,然后尝试打印该值。 Just swap the statements in while loop. 只需在while循环中交换语句。 If you want to print whole list, you should also change the condition of while loop. 如果要打印整个列表,还应该更改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