简体   繁体   中英

toString() method for my linked list only prints the first element

I'm implementing my own java.util.linkedlist from scratch so I'm not using any of the java.util.linkedlist capabilities. That being said, I'm currently trying to create my own toString method. This is my node class

private static class Node<T>{ 

  private T data; 
  private Node<T> next; 

  public Node(T d){ 
     next= null; 
     data = d; 
  }

  public Node(T d, Node<T> n){
     data = d; 
     next = n; 
  }

  public T getData(){ 
     return data; 
  }

  public void setData(T d){ 
     data = d; 
  }

  public Node<T> getNext(){ 
     return next; 
  }

  public void setNext(Node<T> n){ 
     next = n; 
  }
}

and this is my listclass

  private Node<T> start;
  private int size; 
  public ListNoOrder() {
  start = null; 
  size = 0;  
}

public void add(T newElt) {

  Node<T> temp = new Node<T>(newElt); 
  Node<T> current = start; 

  try{ if (newElt==(null));}
  catch (Exception illegalArgumentException){
     throw new IllegalArgumentException();}

  if (start == null){ 
     start = new Node<T>(newElt, null); 
  }

  if(current != null){ 
     while (current.next != null){ 
        current.setNext(temp); 
     }
  }
  size++; 
}

public int length() {
   return size;}

and my toString method so far

 public String toString() {
  String toPrint = ""; 
  Node <T> current = start; 

  while (current != null){ 
     toPrint += current.getData(); 
     if (current.next != null)
        toPrint += " ,"; 
     current = current.getNext(); 
  }
 return toPrint; 
}

when I test the method it only prints the first element of the list.

mockList = 7, 8, 15, 62, 38, 3 whatItsPrinting = 7,

I've been struggling for hours.

In your add method you are setting just start variable at the beginning here

start = new Node<T>(newElt, null); 

but you never set next nodes because next of start is null so the following condition is never true

if(current != null){ 
    while (current.next != null){  // this one!
        current.setNext(temp); 
    }
}

Even if this condition would be true it would not really worked - what you need to do here is to get the last node (node without next and to set only it's next ). Something like

if(current != null) {
    while(current.getNext() != null) {
        current = current.getNext();
    }
    current.setNext(new Node<T>(newElt));
}
else {
    current = new Node<T>(newElt, null); // because current is start
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM