Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
打印LinkedList java中的第一个元素_Java - Fatal编程技术网

打印LinkedList java中的第一个元素

打印LinkedList java中的第一个元素,java,Java,在给定的代码中,除了显示器没有打印插入的第一个元素外,其他一切都正常工作 public void display() { Link pcurrent = pfirst; while(pcurrent.next!= null) { System.out.println(pcurrent); pcurrent = pcurrent.next; } } 按顺序插入元素:100200300400-> 它将其输出为: //not

在给定的代码中,除了显示器没有打印插入的第一个元素外,其他一切都正常工作

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

    }
    }
按顺序插入元素:
100200300400
-> 它将其输出为:

//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;
    }
}
在这里,我改变了在循环之前如何初始化
pccurrent
,改变了循环条件,并改变了循环体内部事件的顺序

作为for循环,这可能更好:

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

如果您还想打印
pfirst
(这听起来像您实际想要做的),那么只需保持当前的
pccurrent
初始化,并仍进行其他更改。

我假设您正在列表前面插入元素。 在while循环中交换语句

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

使用代码时,首先推进指针,然后尝试打印值。只需交换
循环中的语句即可。如果要打印整个列表,还应更改
while
循环的条件

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

交换打印和分配行。@PM77-1-不够。还需要更改
while
条件,并且(如果打印
pfirst
应该被抑制)也需要在循环之前更改初始化。具体取决于它的用途,但是如果你想让人觉得有趣的话,你可以实现iterable,这将使你的循环更具可读性且无1-off错误。从pfirst开始。next也会产生NullPointerException,是的,我也想打印pfirst,在转换到下一个元素之前,我移动了打印行,这样做也无济于事,因为现在我确实打印插入的最后一个元素,但不是第一个element@GurupratapSaini-您是否在循环测试期间更改了
?如果是这样的话,我看不出这怎么会产生NPE。如果你想打印整个列表,请检查我的回答这将无法打印最后一个元素。您已将一个问题替换为另一个问题。看起来非常像我的答案(一旦有人阅读了最后一段)。:)