我查看了有关此问题的其他帖子,原因似乎是没有正确分配内存/解除引用。输出仅显示存储在第一个节点中的数据,该节点在Main函数中创建。但是,我使用new
分配每个新节点。以下是我的代码,如果有人可以请看看:
struct people{
Name name;
double height;
int weight;
};
struct Queue{
people* ppl;
int data;
Queue* next;
};
void print(Queue * queueHead){
Queue * traverse = queueHead;
while(traverse!=NULL){
cout << "height " << traverse->ppl->height << endl;
traverse = traverse->next;
}
}
void addNode(Queue*& queue, const people ppl){
people* node = new people;
node->name = ppl.name;
node->height = ppl.height;
node->weight = ppl.weight;
Queue* traverse = queue;
Queue* new_node = new Queue;
while(traverse!= NULL){
traverse= traverse->next;
}
new_node->ppl = node;
new_node->next = NULL;
traverse=new_node;
traverse->next = NULL;
}
int main(){
Queue * queueHead = new Queue;
people * node = new people;
node->name = Ashley;
node->height = 5.5;
node->weight = 125;
queueHead->ppl = node;
queueHead->next = NULL;
node=NULL;
people node2 = {
.name = Peter,
.height = 5.8,
.weight = 145
};
people node3 = {
.name = Bill,
.height = 6.0,
.weight = 160
};
people node4 = {
.name = Mike,
.height = 6.2,
.weight = 150
};
people node5 = {
.name = Chris,
.height = 6.2,
.weight = 140
};
addNode(queueHead,node2);
addNode(queueHead,node3);
addNode(queueHead,node4);
addNode(queueHead,node5);
//queueHead->next = NULL;
print(queueHead);
答案 0 :(得分:0)
在addNode
Queue* traverse = queue;
是queue
地址的副本,这意味着他们指向同一个地方,但这并非全部有用。作为一个例子,请注意循环迭代到列表末尾会发生什么:
while(traverse->next != NULL){
traverse= traverse->next;
}
遍历列表,但每次都会让traverse
指向NULL,并且它与列表中的任何内容分开。
traverse=new_node;
将新节点分配给traverse
,但遍历是一个局部变量,仅指向与最后一个节点next
相同的内容。遍历超出范围,列表未更新,新节点泄露。
但是
Queue** traverse = &queue;
让traverse
始终指向next
,而不仅仅是下一个的副本。如果您更新*traverse
,则可以修改列表。例如,
void addNode(Queue*& queue, const people ppl){
// I think you dropped a & here const pass by value isn't all that useful.
people* node = new people;
node->name = ppl.name;
node->height = ppl.height;
node->weight = ppl.weight;
// the above should be done in a people copy constructor
Queue** traverse = &queue;
Queue* new_node = new Queue;
while((*traverse)!= NULL){
traverse= &(*traverse)->next; //traverse points at next instead of
// being a copy.
}
new_node->ppl = node;
new_node->next = NULL;
*traverse=new_node; // pointing what traverse points at at the new node
(*traverse)->next = NULL; // this should really be done in a Queue constructor
}
答案 1 :(得分:-2)
您的添加节点功能实际上从未将新节点添加到现有队列中。
试试这个
void addNode(Queue*& queue, const people ppl){
people* node = new people;
node->name = ppl.name;
node->height = ppl.height;
node->weight = ppl.weight;
Queue* traverse = queue;
Queue* new_node = new Queue;
while(traverse->next != NULL){
traverse= traverse->next;
}
new_node->ppl = node;
new_node->next = NULL;
traverse->next = new_node;
}