我正在尝试创建一个在链表末尾添加节点的函数。然而,每次我运行它时,我都会遇到运行时错误,并且不知道我的错误在哪里。这是我的代码:
Edge* append(Edge *head, int origin, int destination, int weight) {
Edge *temp = new Edge;
temp = head;
Edge *node = new Edge;
while (temp->next != NULL){
temp = temp->next;
}
node->vert1 = origin;
node->vert2 = destination;
node->weight = weight;
node->next = NULL;
if (head == 0) {
head = node;
}
else if (head != 0){
node = temp;
}
return head;
}
更新:
这是Edge结构:
struct Edge {
int vert1;
int vert2;
int weight;
Edge *next;
};
这是主要功能:
int main(){
Edge *e = append(NULL, 1,4,5);
}
答案 0 :(得分:1)
我注意到的第一件事是你在之后检查头是否为NULL 你已经取消引用它。您将temp设置为head,然后检查temp-> next是否为NULL。如果head为NULL,则崩溃。 此外,你的其他如果是多余的。如果head不等于0,那么它必须与0不同。第三件事是,最后你将node设置为temp,但我认为你想要做的是在node旁边设置temp->
Edge* append(Edge *head, const int origin, const int destination, const int weight) {
Edge *temp = head;
Edge *node = new Edge;
node->vert1 = origin;
node->vert2 = destination;
node->weight = weight;
node->next = NULL;
if (!head) {
return node;
}
while (temp->next != NULL){
temp = temp->next;
}
temp->next = node;
return head;
}
修改强> 你的代码也有内存泄漏。你永远不会释放你在第一行为temp保留的内存。但是,此处无需创建新Edge。
答案 1 :(得分:0)
当你宣布:
Edge *temp = new Edge;
然后你将temp重新分配到头部:
temp = head;
因此,如果传入空head
参数,则会在
while (temp->next != NULL){
看起来这种重新分配并不是你真正想做的事情,因为除此之外逻辑还没有解决。试试这个:
Edge* append(Edge *head, int origin, int destination, int weight) {
// create your new node
Edge *node = new Edge;
node->vert1 = origin;
node->vert2 = destination;
node->weight = weight;
node->next = NULL;
// if there is no head, this is the head
if (head == NULL) {
head = node;
return node;
}
// else walk to the end and set this as as the new tail node
// NOTE: this can be optimized by having your linkedlist implementation
// store the pointer to the tail.
Edge *temp = head;
while (temp->next != NULL){
temp = temp->next;
}
temp->next = node;
return node;
}