gpt4 book ai didi

java - 添加到链接列表的末尾

转载 作者:行者123 更新时间:2023-12-01 13:29:18 31 4
gpt4 key购买 nike

我目前正在研究 Java 中的链表。我有一个示例程序,对于某些输入可以按预期工作,而对于其他输入则完全不起作用。

//Constructor in class List of People
ListOfPeople() {
Person listHead = new Person("LIST HEAD");
personList = listHead;
lastPerson = listHead;
numberPeople = 0;
}
//Adds person to the beginning of the list
public void addFirst(Person newP) {
newP.next = personList.next;
personList.next = newP;
numberPeople++;
}
//Adds person to the end of the list
public void addLast(Person lastP) {
lastPerson.next = lastP;
lastPerson = lastP;
numberPeople++;
}

对于 Person 类,我有以下代码:

//From the Person class
String name;
Person next;

Person(String n) {
name = n;
next = null;
}

假设我将两个不同的人添加到列表的开头:

Person mulan = new Person("Mulan");
myFriends.addFirst(mulan);
Person mushu = new Person("Mushu");
myFriends.addFirst(mushu);

然后,代码就可以正常运行了。我得到的输出是:“Mushu,Mulan”。但是,如果我在列表的开头添加一个人,在列表的末尾添加另一个人,我会收到 NullPointerException。如果我尝试在两个 Person 对象上调用 addLast(String name) 方法,似乎没有问题。

非常感谢任何提示!

最佳答案

尝试如下:

 // I left out getters and setters for brevity.
class PersonNode {
Person current;
PersonNode next;
PersonNode previous;
}

class PersonList {
PersonNode head;
PersonNode tail;

public PersonList(){
head.previous = null;
tail.next = null;
}
void addFront(Person p){
if (head.person == null) {
head.person = p;
}
else {
PersonNode temp = head; head= new PersonNode(p);
temp.previous = head; head.next = temp;
}
}
void addBack(Person p) {
if (tail.person == null) {
tail.person = p;
}
else {
PersonNode temp = tail;
tail= new PersonNode(p);
temp.next = tail;
tail.previous = temp;
}

int count() {
int c = 0;
for(PersonNode n = head; head.next != null; n = head.next){
if (n.Person !=null){
++c;
}
}
return c;
}
}

关于java - 添加到链接列表的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21657194/

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