【发布时间】:2016-01-21 02:37:21
【问题描述】:
这是一个正向打印 LinkedList 的函数的代码。
void DLinkedList::printForwards(int age)
{
DNode * current;
current = header->next;
while (current != NULL)
{
if (current->elem->getAge() <= age) {
cout << current->elem->getName() << ", ";
}
current = current->next;
}
cout << endl;
}
这里是 DNode 类
typedef Person* Elem;
class DNode { // doubly linked list node
private:
Elem elem; // node element value
DNode* prev; // previous node in list
DNode* next; // next node in list
friend class DLinkedList; // allow DLinkedList access
};
这是 Person 类
class Person {
public:
Person(int age, string first, string last){
setAge(age);
setFirstname(first);
setLastName(last);
}
void setAge(int age){
this->age = age;
}
void setFirstname(string first){
firstName = first;
}
void setLastName(string last){
lastname = last;
}
int getAge(){
return age;
}
string getName(){
return firstName + " " + lastname;
}
private:
string firstName, lastname;
int age;
};
这是我的主要内容
int main(){
DLinkedList list;
Person * ryan= new Person(19, "Ryan", "Temple");
list.addFront(ryan);
list.printForwards(100);
}
这行代码给程序带来了麻烦。
if (current->elem->getAge() <= age)
elem 的值被设置为 NULL。 当电流被初始化时,它被指向正确的节点。 但是在 if 语句中访问 current 会将其值设置为 NULL。
有人可以帮帮我吗?
编辑: 这里是 addFront 函数
void DLinkedList::add(DNode* v, Elem& e) {
DNode* u = new DNode;
u->elem = e; // create a new node for e
u->next = v; // link u in between v
u->prev = v->prev; // ...and v->prev
v->prev->next = u;
v->prev = u;
}
添加前面
void DLinkedList::addFront(Elem& e) // add to front of list
{
add(header->next, e);
}
【问题讨论】:
-
嗯?将 elem 的值设置为 null 是什么意思?您似乎在说 elem->getAge() 将 elem 设置为空。但是,几句话之后,您还说在 if 语句中访问 current 会将其值设置为 null。那是什么。如果 current 为 null,你怎么知道 elem 设置为 null?
-
请贴上addFront函数的代码。这就是可能出现错误的地方。
-
@iheanyi 当前指向正确的节点,但是当我访问该元素时,它正在从 NULL 访问它。如果这有意义
-
不完全。您无法在 null 处访问任何内容。看来您的意思是 current 不是 null 而 elem 是 null。
-
但无论如何,就像 FrankM 建议的那样,为 addFront 发表评论。如果您遇到 elem 为 null 的问题,那很可能是源头。
标签: c++ null linked-list