我在C中使用链表的插入方法遇到一些麻烦。它似乎仅添加在表的开头。我进行的任何其他插入操作都会失败。而且这个CodeBlocks调试器很难理解,我仍然不明白。它从不给我值(value),只是给内存中的地址。无论如何,这是我的职责。您是否看到失败的任何原因?

/* function to add a new node at the end of the list */
int addNodeBottom(int val, node *head){

    //create new node
    node *newNode = (node*)malloc(sizeof(node));

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

    newNode->value = val;

    //check for first insertion
    if(head->next == NULL){
        head->next = newNode;
        printf("added at beginning\n");
    }

    else
    {
        //else loop through the list and find the last
        //node, insert next to it
        node *current = head;
        while(current->next != NULL)
        {
            if(current->next == NULL)
            {
                current->next = newNode;
                printf("added later\n");
            }
            current = current->next;
        }
    }
    return 0;
}

然后,主要是仅添加929。
   //testing addNodeBottom function
    addNodeBottom(929, head);
    addNodeBottom(98, head);
    addNodeBottom(122, head);
    addNodeBottom(11, head);
    addNodeBottom(1034, head);

最佳答案

此代码将起作用。 samplebias的答案几乎是正确的,但是您需要进行第三次更改:

int addNodeBottom(int val, node *head){

    //create new node
    node *newNode = (node*)malloc(sizeof(node));

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

    newNode->value = val;
    newNode->next = NULL;  // Change 1

    //check for first insertion
    if(head->next == NULL){
        head->next = newNode;
        printf("added at beginning\n");
    }

    else
    {
        //else loop through the list and find the last
        //node, insert next to it
        node *current = head;
        while (true) { // Change 2
            if(current->next == NULL)
            {
                current->next = newNode;
                printf("added later\n");
                break; // Change 3
            }
            current = current->next;
        };
    }
    return 0;
}

更改1:必须将newNode->next设置为NULL,这样我们才不会在列表末尾插入无效的指针。

更改2/3:将循环更改为无穷循环,当我们找到最后一个元素时,该循环将使用break;跳出。请注意while(current->next != NULL)与以前的if(current->next == NULL)相矛盾。

编辑:关于while循环,这种方式要好得多:
  node *current = head;
  while (current->next != NULL) {
    current = current->next;
  }
  current->next = newNode;
  printf("added later\n");

关于最后是C链表插入节点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5797548/

10-10 13:32
查看更多