如何在我的代码中打印出节点?

时间:2016-01-05 19:24:57

标签: 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) 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;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

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

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