Reputation: 761
I am currently studying up on linked lists in Java. I have a sample program that works as expected for certain input, and not at all for other input.
//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++;
}
For the Person class, I have the following code:
//From the Person class
String name;
Person next;
Person(String n) {
name = n;
next = null;
}
Suppose I add two different people to the beginning of the list:
Person mulan = new Person("Mulan");
myFriends.addFirst(mulan);
Person mushu = new Person("Mushu");
myFriends.addFirst(mushu);
Then, the code works without problems. And I get the output: "Mushu, Mulan". HOWEVER, if I add one person at the beginning of the list, and another at the end, I get a NullPointerException. If I try to invoke the addLast(String name) method on both Person objects, there seems to be no problem.
Any tips are highly appreciated!
Upvotes: 0
Views: 167
Reputation: 31873
Try something like:
// 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;
}
}
Upvotes: 1