Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.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
Java 如何打印代码中的节点?_Java_Linked List - Fatal编程技术网

Java 如何打印代码中的节点?

Java 如何打印代码中的节点?,java,linked-list,Java,Linked List,我无法找到一种基于代码打印所有节点的方法。如何根据当前代码将它们全部打印出来 import java.io.*; import java.util.*; import java.text.*; public class Linkedlist { static public class Node { Node next; String data; } public static void main (String[] args) t

我无法找到一种基于代码打印所有节点的方法。如何根据当前代码将它们全部打印出来

import java.io.*;
import java.util.*;
import java.text.*;

public class Linkedlist
{
    static public class Node
    {
        Node next;
        String data;
    }
    public static void main (String[] args) throws IOException
    {
        BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
        Node head = null;
        Node node = new Node();
        while(true)
        {
            String str = stdin.readLine();
            if (!str.equals("fin"))
            {
                node.data = str;
                node.next = head;
                head = node;
                node = new Node();
            }
            else
            {
                break;
            }
        }
    }
}

您需要保留对头部节点的引用。现在,您只需在每次添加新项目时重新设置它。然后你可以这样做:

Node current = head;
while (current != null) {
  System.out.println(current.data);
  current = current.next;
}

您已经显示了创建链表的代码,但没有显示遍历链表的代码。到目前为止,您尝试了什么?您是否在询问如何调用
System.out.println(node.data)
?或者你有其他问题吗?这是我老师交给我的基本实现我想我误解了你,我自己写了上面的代码,基于老师给我们展示的一个非常简单的东西