向单向链表末尾添加节点

3

我在向单链表添加节点时遇到了问题,因为某些原因当列表为空时,

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");
     }
}

注意 headcurrent 的类型。也许你想要 node *current = *head;。那么当你在开头添加它时会发生什么?目前你只是打印,但没有重新分配/移动 head。实际上,在另一种情况下你这样做了... - Pynchia
@Pynchia,我在if语句处收到了一个段错误。 - user5464683
我能看到。请再读一遍我的评论 :) - Pynchia
@Pynchia 我肯定是漏了什么哈哈,我不知道你在指什么。对不起,你能详细说明一下吗? - user5464683
当列表为空时,head 指向 NULL 还是始终存在一个虚拟元素在开头?(即 head 指向一个虚拟元素) - Pynchia
@Pynchia 它被初始化为 node * head = NULL; - user5464683
1个回答

1
假设一个空列表具有 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");
    }
}

指向指针的指针往往很棘手,容易出错。 - Pynchia
一个更合适的消息,而不是“添加在开头”,应该是“第一个节点”。你的代码没有问题。这只是一个建议。 - alvits

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接