首先,代码显示它class Event
是独立的。也就是说,head
并且nxt
是对象本身的一部分。如果您希望使用相互链接但不维护head
外部的对象的链接列表,那么我将执行以下操作...
// event.cpp
event::event() {
head = NULL;
}
event::event(int date, string name): date(date), name(name) {
head = NULL;
}
event::event(event *prev, int date, string name): date(date), name(name) {
if (prev->head != NULL) {
this->head = prev->head;
} else {
prev->head = this->head = prev;
}
prev->nxt = this;
this->nxt = NULL;
}
使用它的一个例子如下:
event *tailEvent = new event(1, 'first');
event *nextEvent = new event(tailEvent, 2, 'second');
event *thirdEvent = new event(nextEvent, 3, 'third');
...
tailEvent = lastEvent;
等等等等。因此,tailEvent->head
将始终指向第一个创建的事件,并且tailEvent->nxt
将在列表中跟随。
但是...这很容易出错,所以我建议将列表本身保留在外面,如果可能的话使用 STL。有关示例,请参阅学习 C++:示例链接列表。
编辑:
更好的方法: -
class Event {
private:
Event *next;
int date;
string name;
public:
Event() {};
Event(int date, string name) : date(date), name(name) {};
setNext(Event *next) { this->next = next; };
int date() { return date; };
string name() { return name; };
Event *next() { return next; };
};
class EventList {
private:
Event *head;
public:
EventList() { head = NULL };
void add(int date, string name);
Event *head() { return head; }
}
void EventList::add(int date, string name) {
Event *newEvent = new Event(date, name);
newEvent->setNext(NULL);
Event *tmp = head;
if (tmp != NULL) {
while (tmp->next() != NULL) tmp = tmp->next();
tmp->setNext(newEvent);
} else {
head = newEvent;
}
}