我无法找到基于代码打印出所有节点的方法。我该如何根据当前代码将它们全部打印出来
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;
}
}
}
}
您需要保留对head节点的引用。现在,您只需在每次添加新项目时重新设置它。然后你可以做这样的事情:
Node current = head;
while (current != null) {
System.out.println(current.data);
current = current.next;
}