我目前正在研究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”。 HOWEVER ,如果我在列表的开头添加一个人,最后添加另一个人,我会得到一个NullPointerException。如果我尝试在两个Person对象上调用addLast(String name)方法,则似乎没有问题。
任何提示都非常感谢!
答案 0 :(得分:1)
尝试类似:
// 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;
}
}