C语言 将节点添加到单链表的末尾



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

if(current->next == NULL)

当列表为空时,

被跳过,当我显示列表时,这会导致segfault…我真的很困惑为什么它被跳过了有什么想法吗?

 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 noden");
         exit(-1);
     }
     InitNodeInfo(newNode, name, groupSize, inRest);
     node *current = head;
     //check for first insertion
     if (current->next == NULL) {
         current->next = newNode;
         printf("added at beginningn");
     } 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 latern");
           *head = current;
     }
     if (debug == FALSE) {      //debug mode...
         printf("Pushed the value %d on to the stackn", groupSize);
     } else {
         printf("nnATTENTION : Group cannot be added, the name entered already exists!nn");
     }
}

假设一个空列表有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 noden");
        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 beginningn");
    }
    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("appendedn");
    }
    // mark the element as the last one
    newNode->next = NULL;
    if (debug == FALSE) {//debug mode...
         printf("Pushed the value %d on to the stackn", groupSize);
    }
    else{
        printf("nnATTENTION : Group cannot be added, the name entered already exists!nn");
    }
}

相关内容

  • 没有找到相关文章

最新更新