gpt4 book ai didi

c - 我在链表的末尾创建一个垃圾节点只是为了指定 NULL。我怎样才能修改我的代码来防止这种情况发生?

转载 作者:太空宇宙 更新时间:2023-11-04 03:39:28 27 4
gpt4 key购买 nike

#include<stdio.h>
#include<stdlib.h>

typedef struct Node{
int val;
struct Node* next;
} Node;

void add_at_end(Node* head, int val){
Node* newNode = malloc(sizeof(Node));
newNode -> next = NULL;

Node* temp = head;

if(head -> next == NULL){
head ->val = val;
head -> next = newNode;
}

else{
while(temp -> next != NULL){
temp = temp -> next;
}
temp -> next = newNode;
temp -> val = val;
}
}

void display(Node* l){
while(l->next != NULL){
printf("%d -->", l->val);
l = l->next;
}
printf("End\n");
}

正如我在问题中所说,我在最后创建了一个无用的节点,只是为了指定 NULL。我怎样才能删除该功能?我知道我在 add_at_end 函数中做错了什么,但我无法纠正它。帮助将不胜感激。谢谢

编辑:

#include<stdio.h>
#include<stdlib.h>

typedef struct Node{
int val;
struct Node* next;
} Node;

typedef struct List{
Node* head;
} List;

void add_at_end(List* l, int val){
Node* newNode = malloc(sizeof(Node));
newNode -> next = NULL;
newNode -> val = val;

Node* temp = l->head;

if(temp == NULL){
l->head = newNode;
}

else{
while(temp->next != NULL){
temp = temp -> next;
}
temp -> next = newNode;
}

}

void display(List* l){
Node* t = l -> head;
while(1){
printf("%d\n", t->val);
if(t->next == NULL) break;
t = t->next;
}
}
int main(){
List l;
l.head = NULL;

add_at_end(&l, 10);

add_at_end(&l, 20);

add_at_end(&l, 30);

display(&l);
return 0;
}

这是我的最终代码。

我需要帮助将节点添加到列表的中间。我该怎么做?

最佳答案

您的节点使用情况很困惑。当您创建一个新节点时,该值应存储到该节点中,并将该节点链接到列表中。相反,您正在做的是尝试将值添加到最后一个节点,然后链接到一个虚拟节点。这有点令人费解,所以我不确定我是否已经清楚地解释了你所做的事情。 add_to_end 应该更像这样:

add_to_end (Node** head, int val)
{
Node* temp;
Node* newNode = malloc(sizeof(Node));
if (!newNode) {
/* Error */
}

newNode->val = val;
newNode->next = NULL;

if (!*head) {
/* empty list. Just make new node the head */
*head = newNode;
} else {
/* Find the end of the list */
temp = *head;
while (temp->next) {
temp = temp->next;
}

/* temp is now the last node. Chain new node after it */
temp->next = newNode;
}
}

关于c - 我在链表的末尾创建一个垃圾节点只是为了指定 NULL。我怎样才能修改我的代码来防止这种情况发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29822029/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com