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

标签 c struct linked-list nodes

#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/

相关文章:

c - C的RAD环境? (不是 C++,只是 C)

c - #include "existing file"失败 : no such file (C)

c - 为什么链表的变量必须是指针

java链表复制构造函数

c++ - 链表头指针在传递给函数 c++ 时发生变化

c++ - SDL - 音频回调函数有时没有及时调用

python - 在 Python C API 中使用多个模块/类型?

C:复制结构/数组元素

c++ - 将文本文件中的数据提取到结构中

C 将结构中的嵌套结构传递给函数?