gpt4 book ai didi

c - 将节点添加到单链表的末尾

转载 作者:行者123 更新时间:2023-12-02 03:21:13 24 4
gpt4 key购买 nike

我在将节点添加到单链表时遇到问题,由于某种原因

if(current->next == NULL)

当列表为空时被跳过,这会在我显示列表时导致段错误...我真的很困惑为什么它会被跳过任何想法?

 void addToList(node** head, char name[30], int groupSize, boolean inRest){
//create new node
node *newNode = (node*)malloc(sizeof(node));

if (newNode == NULL) {
fprintf(stderr, "Unable to allocate memory for new node\n");
exit(-1);
}

InitNodeInfo(newNode, name, groupSize, inRest);
node *current = head;
//check for first insertion
if (current->next == NULL) {
current->next = newNode;
printf("added at beginning\n");
} else {
//else loop through the list and find the last
//node, insert next to it
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
printf("added later\n");
*head = current;
}

if (debug == FALSE) { //debug mode...
printf("Pushed the value %d on to the stack\n", groupSize);
} else {
printf("\n\nATTENTION : Group cannot be added, the name entered already exists!\n\n");
}
}

最佳答案

假设一个空列表有 head == NULL

这应该可行(我现在没有办法尝试)

 void addToList(node** head, char name[30], int groupSize, boolean inRest){
//create new node
node *newNode = (node*)malloc(sizeof(node));

if(newNode == NULL){
fprintf(stderr, "Unable to allocate memory for new node\n");
exit(-1);
}

InitNodeInfo(newNode, name, groupSize, inRest);
node *current = *head;
//check for first insertion
if(current == NULL){
// make head point to the new node
*head = newNode;
printf("added at beginning\n");
}
else
{
//else loop through the list and find the last
//node, insert next to it
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
printf("appended\n");
}
// mark the element as the last one
newNode->next = NULL;

if (debug == FALSE) {//debug mode...
printf("Pushed the value %d on to the stack\n", groupSize);
}
else{
printf("\n\nATTENTION : Group cannot be added, the name entered already exists!\n\n");
}
}

关于c - 将节点添加到单链表的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33224412/

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