这是我的节点类
public class listNode {
String data;
listNode next;
public listNode(String data, listNode next) {
this.data = data;
this.next = next;
}
public String toString(){
return data;
}
}
她的是我的列表类
public class List {
listNode head;
public List(){
head = null;
}
public void addLast(String target){
if(head == null){
head = new listNode(target,head);
}
while(head.next != null){
head = head.next;
}
head.next = new listNode(target,null);
}
}
打印方法:
public void print(){
while(head != null){
System.out.println(head.toString());
head = head.next;
}
}
当我在main函数中使用这种方法时,它总是只打印链表的最后两个值,我很困惑。
示例:
l1.addLast("a");
l1.addLast("b");
l1.addLast("c");
它只打印
b,c
以下代码不正确。您不应该更改头部对象。使用其他对象。
while(head.next != null){
head = head.next;
}
应该是这样的:
class List {
listNode head;
public List(){
head = null;
}
public void addLast(String target){
if(head == null){
head = new listNode(target,head);
}
else {
listNode last = head;
while(last.next != null){
last = last.next;
}
last.next = new listNode(target,null);
}
}
}
您有两个错误。
public void addLast(String target){
if(head == null){
head = new listNode(target,head);
return; // Mistake 1 - you need to return here - nothing more is needed.
// If you don't return. addLast will create 2 listNode's for the first entry.
}
listNode h = head; // Mistake 2 - Use a temp instead of head. head will
//no longer point to the start otherwise.
while(h.next != null)
{
h = h.next;
}
h.next = new listNode(target,null);
}
评论中指出了这些错误。
第一个错误并不严重。第二个是.