gpt4 book ai didi

Java - 遍历链表仅返回null

转载 作者:行者123 更新时间:2023-12-02 05:23:51 24 4
gpt4 key购买 nike

我正在研究链表。在《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();
}
}

最佳答案

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

关于Java - 遍历链表仅返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26248851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com