我正在研究链接列表。在Cracking the Coding Interview一书的帮助下,我创建了以下代码来创建链接列表,在其末尾添加元素并打印元素。但是,当我运行代码时,它只返回" null"而不是打印列表,即" Sanchez"。 "厄齐尔"和#34; Welbeck"。帮助
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();
}
}
答案 0 :(得分:2)
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 != 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
Welbeck
答案 1 :(得分:0)
在PrintList中,迭代每个元素,最后一次迭代丢失,所以我改变了循环条件
void PrintList(){
Node n = this;
while (n != null){
System.out.println(n.PlayerName + "\n");
n = n.next;
}
}
答案 2 :(得分:0)
我很确定问题出在你添加到链表时。
Node n = this;
这指向了班级本身,这不是一个节点
您应该在表示第一个Node的类中实现Node变量。所以像这样:
public class CreateLinkedList{
static class Node{
//all this stuff seemed fine
}
Node first = null;//represents first item
//Method to insert a Node
void InsertNodeAtEnd(String PlayerName){
Node transition = new Node(PlayerName);
Node n = first;
if(n!=null){
while(n.next != null){
n = n.next;
}
n.next = transition;
}
else
first = transition;
//Method to print all elements of linked list
void PrintList(){
Node n = first;
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();
}
}'
答案 3 :(得分:0)
在printList中迭代时使用以下作为检查条件:
N!= NULL
而不是
n.next!= null
在您的代码中,当您比较下一个节点而不是当前节点时,循环正在跳过最后一次迭代。
正确的方法是:
//Method to print all elements of linked list
void PrintList(){
Node n = this;
while (n != null){
System.out.println(n.PlayerName + "\n");
n = n.next;
}
}