Rconno Rconno - 1 month ago 15
Java Question

Singly Linked Lists Print method only prints the first object (Java)

Here are my two classes NameNode and NameList. My problem comes with the print() method in the NameList class. If I have two names lets say "Lee" and "Jim" the output using said method only prints out "Lee". Im not sure if its the append method failing to add to the list or if there is a step error causing tmp to not advance to the next object in the list. Any help is appreciated.

public class NameNode {
private String lastName;
private NameNode next;
public NameNode(String lastName, NameNode toNext)
{
this.lastName = lastName;
this.next = toNext;
}
public String getName()
{
return lastName;
}
public NameNode getNext()
{
return next;
}
public void setNext(NameNode next)
{
this.next = next;
}
public String toString()
{
return lastName;
}
}




public class NameList {
private NameNode names;
public NameList()
{
names = null;
}
public boolean isEmpty()
{
return names == null;
}
public void append(String name)
{
if(names == null)
{
names = new NameNode(name,null);

}
else
{
NameNode tmp = names;
//tmp = names;
while(tmp.getNext() != null)
{
tmp = tmp.getNext();
tmp.setNext(new NameNode(name,null));

}

}
null
}

public void print()
{
NameNode current = names;
while(current != null)
{
System.out.println(current.getName());
current = current.getNext();
}

}
}

Answer

You have error in your append function of NameList. In your code, when you append the second name, the program goes to else statement, where it evaluates false for the condition in while loop and never appends the second node. Thus your code is always able to enter only first element. Refer the corrected append function, hopefully it would do the job.

public void append(String name)
{
  if(names == null)      {
    names = new NameNode(name,null);
  }
  else{
    NameNode tmp = names;
    while(tmp.getNext() != null){
      tmp = tmp.getNext();
    }
    tmp.setNext(new NameNode(name,null));
  }
}
Comments