[英]Adding a node to a Linked List gives a runtime error in C++
我正在嘗試創建一個函數,該函數將在鏈表的末尾添加一個節點。 但是,每次運行它時,都會遇到運行時錯誤,並且不知道我的錯誤在哪里。 這是我的代碼:
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);
}
我注意到的第一件事是, 在已經取消引用head 之后 ,您檢查它是否為NULL。 您將temp設置為head,然后檢查temp-> next是否為NULL。 如果head為NULL,則崩潰。 此外,您的else是否多余。 如果head不等於0,那么它必須不同於0。第三件事是,最后將node設置為temp,但是我認為您想要做的就是將temp-> next設置為node。
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。
當您聲明:
Edge *temp = new Edge;
然后,您重新分配臨時負責人:
temp = head;
因此,如果你在一個空傳head
PARAM,你會崩潰
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.