以下是我采取的方法。当然,这有点做作,因为我不知道您的实际功能。我还用初始全局变量表示 pHead,并使用具有超出范围值的年龄来指示列表的头部。
对于列表的头部,我使用了一个特殊的构造函数。
有更好的方法可以做到这一点,但是在这个快速而肮脏的实现中,我需要一些东西来表明在递归期间退出时,我知道什么时候我已经一直支持到列表的头部。
#include <string>
class Person {
private:
std::string firstname;
std::string lastname;
int age;
Person* next;
public:
Person (void); // constructor for the pHead
~Person (void);
Person(std::string, std::string, int); // standard constructor used
std::string getFirstname(void) { return firstname; };
std::string getLastname(void) { return lastname; }
void setNext(Person *newNext) { next = newNext; }
Person* getNext() { return next; }
Person *addToListAt (Person *personList);
void addToListAtEnd (Person *personList);
void Person::insertListAfter (Person *personList);
bool isHeadOfList (void);
};
Person pHead = Person();
// special constructor used to create the head to a linked list
Person::Person ()
{
age = -1;
next = 0;
}
// standard constructor used to create a list item.
Person::Person (std::string sFirstName, std::string sLastName, int myAge)
{
if (myAge < 0) myAge = 0;
firstname = sFirstName;
lastname = sLastName;
age = myAge;
next = 0;
}
Person::~Person ()
{
next = 0;
age = 0;
}
void exterminateStartingFrom(Person* person)
{
Person* nextPerson;
nextPerson = person->getNext();
if(nextPerson){
exterminateStartingFrom(nextPerson);
}
if (! person->isHeadOfList())
delete person;
}
Person *Person::addToListAt (Person *personList)
{
Person* nextPerson;
nextPerson = personList->getNext();
personList->setNext (this);
return nextPerson;
}
void Person::insertListAfter (Person *personList)
{
Person* nextPerson;
nextPerson = personList->getNext();
personList->setNext (this);
next = nextPerson;
}
void Person::addToListAtEnd (Person *personList)
{
Person* nextperson;
nextperson = personList->getNext();
if(nextperson){
addToListAtEnd (nextperson);
} else {
personList->setNext (this);
}
}
bool Person::isHeadOfList (void)
{
// we use a special age to represent the head of the list
// the head does not contain any data except for point to first item
// in the list.
return (age < 0);
}
int main(int argc, char * argv[])
{
Person *newPerson = new Person("first_1", "last_1", 11);
newPerson->addToListAtEnd (&pHead);
newPerson = new Person("first_2", "last_2", 22);
newPerson->addToListAtEnd (&pHead);
newPerson = new Person("first_3", "last_3", 33);
newPerson->addToListAtEnd (&pHead);
Person *itemPerson = pHead.getNext();
newPerson = new Person("first_11", "last_11", 12);
newPerson->insertListAfter (itemPerson);
exterminateStartingFrom(&pHead);
return 0;
}