【发布时间】:2014-10-08 03:38:38
【问题描述】:
我正在研究链表。在《Cracking the Coding Interview》一书中的帮助下,我创建了以下代码来创建链表,将元素添加到其末尾并打印元素。但是,当我运行代码时,它只返回“null”而不是打印列表,即“Sanchez”。 “厄齐尔”和“维尔贝克”。帮忙?
public class CreateLinkedList{
static class Node{
String PlayerName;
Node next = null;
//Constructor
Node(String PName){
PlayerName = PName;
}
//Method to insert a Node
void InsertNodeAtEnd(String PlayerName){
Node transition = new Node(PlayerName);
Node n = this;
while(n.next != null){
n = n.next;
}
n.next = transition;
}
//Method to print all elements of linked list
void PrintList(){
Node n = this;
while (n.next != null){
System.out.println(n.PlayerName + "\n");
n = n.next;
}
}
}
public static void main(String[] args) {
Node first = new Node("Sanchez");
first.InsertNodeAtEnd("Ozil");
first.InsertNodeAtEnd("Welbeck");
first.PrintList();
}
}
【问题讨论】:
-
我只是按照目前的方式运行您的代码,我得到了
Sanchez和Ozil作为输出(仍然缺少一个,但请参阅@Debasish Jana 的答案)。你在哪里得到空值? -
你刚刚发现我的 Eclipse 出了点问题。我知道很奇怪。在 netbeans 中试过,效果很好
标签: java class methods linked-list system.out