Java 添加到链接列表的末尾
我目前正在研究Java中的链表。我有一个示例程序,它在某些输入中按预期工作,而在其他输入中则完全不工作Java 添加到链接列表的末尾,java,linked-list,Java,Linked List,我目前正在研究Java中的链表。我有一个示例程序,它在某些输入中按预期工作,而在其他输入中则完全不工作 //Constructor in class List of People ListOfPeople() { Person listHead = new Person("LIST HEAD"); personList = listHead; lastPerson = listHead; numberPeople = 0; } //Adds person to t
//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);
然后,代码就可以正常工作了。我得到了输出:“木树,木兰”。
但是如果我在列表的开头添加一个人,在列表的末尾添加另一个人,我会得到一个NullPointerException。如果我尝试在两个Person对象上调用addLast(stringname)方法,似乎没有问题
任何提示都非常感谢 试试以下方法:
// 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;
}
}
我缺少你的
ListOfPeople
类的字段和NPE抛出的确切位置。这个级别的NPE在运行调试器时很容易被发现,您应该尝试使用它。这就是说,如果您将带有addFirst
的Person
添加到一个空列表中,,请考虑一下对lastPerson
会发生什么。。。我得到了输出:“Mushu,Mulan”。
请说明如何获取这个名称我在Person类中编写了一个方法:“public void write(){System.out.println(name);}。以及ListOfPeople类中的另一个方法:“public void writeAll(){Person p=personlist.next;for(int I=numberPeople;I>0;I--){p.write();p=p.next;}"