Java 仅打印链表的最后两个值
这是我的节点类Java 仅打印链表的最后两个值,java,linked-list,nodes,Java,Linked List,Nodes,这是我的节点类 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 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);
}
评论中指出了错误
第一个错误并不严重。第二个是。显示实际执行打印的代码。