如何打印LinkedList中的数据

时间:2014-10-10 09:37:37

标签: java

我已经成功地从头开始创建了一个LinkedList。到目前为止,它只能添加数据。没有删除或任何类似的东西。

我可以添加字符串,整数等但是打印我添加的数据时遇到问题。我怎么做?我想我必须首先循环它,但是如何?'

这是我的Node类:

public class Node {
  T data;
  Node<T> nextNode;

  public Node(T data) {
      this.data = data;
  }

  public String toString () {
      return data +"";
  }
}

这是LinkedList类:

public class LinkedList <T> {

Node<T> head;
Node<T> tail;

public void add (T data) {
    // where to add statements. if its empty or not
    Node<T>  node = new Node<T> (data);

    if (tail == null) { // empty list
        // nothng in the node = tail = node;
        head = node;
        tail = node;
    }
    else { // non empty list, add the new boogie train to the tail
        tail.nextNode = node; // new node pointing to tail
        tail = node; // update  
    }   
}

这是主要的。我从Linkedlist创建一个对象并使用通用add方法添加我的数据。但是我如何在屏幕上打印出来?提前谢谢。

public static void main(String[] args) {
    LinkedList<Object> list = new LinkedList<Object> ();
    list.add(15); // boogie1 = head
    list.add(16);
    list.add(10); // boogie end = tail

4 个答案:

答案 0 :(得分:6)

将一个方法toString添加到您的LinkedList类

public String toString() {
    Node<T> curr = head;
    StringBuilder sb = new StringBuilder();
    sb.append("LinkedList [");
    while (curr != null) {
        sb.append(curr.data);
        if (curr.nextNode != null) {
            sb.append(", ");
        }
        curr = curr.nextNode;
    }
    sb.append("]");
    return sb.toString();
}

然后在主方法中调用它:

System.out.println(list.toString());

答案 1 :(得分:1)

您必须覆盖toString()

中的LinkedList<T>方法

答案 2 :(得分:1)

好吧,您可以实现Iterator模式:http://sourcemaking.com/design_patterns/iterator/java/1

或者你只是实现一个方法,可以打印节点元素,或者在每个节点元素上执行某些操作,有点像这样:

public class LinkedList <T> {

   Node<T> head;
   Node<T> tail;

   public void add (T data) {
        ...
   }

   public void forEach(java.util.function.Consumer<T> consumer)
   {
       for(Node<T> currentNode = head; currentNode != null; currentNode = currentNode.nextNode) 
       //I am assuming the last node points to null in nextNode
       // and that head is initialized to null if the list is empty
       {
           consumer.accept(currentNode);
       }
   }
}

然后就这样做

linkedList.forEach(x -> System.out.println(x.toString());

如果一切正常,这应该适用于Java 8。

答案 3 :(得分:1)

在LinkedList类中创建一个getter方法。

public Node getHead() {

    return head;
}

main()

public static void main(String[] args) {

    LinkedList<Object> list = new LinkedList<>();
    list.add(15); // boogie1 = head
    list.add(16);
    list.add(10); // boogie end = tail  

    Node node = list.getHead();

    // Break the loop after the variable reaches null, i.e. end of list.
    // The un initialised instance non-primitive variable is always null by default.
    while(node != null) {

        System.out.println(node);  // Calls the toString() from class Node. 
        node = node.nextNode; // Move to next node.
    }
}  

希望这适合你。