无法将项目添加到链接列表的末尾

标签 c

此代码仅将一个元素添加到列表的末尾(仅创建 head 元素,之后什么也没有)。我的程序有什么问题?我应该在函数中传递两个项目,head 和 item 还是只传递一个?

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct MyList
{
    int x;
    int y;
    struct MyList * next;
}List;

typedef List * Item;

void AddEnd(Item * head);
void PrintList(Item * head);

int main(void)
{
    int response;
    Item head;
    head = NULL;
    while(1)
    {
        printf("1- Print, 2 - Add to End, 3 - exit\n");
        scanf("%d", &response);
        switch(response)
        {
            case 1: PrintList(&head); break;
            case 2: AddEnd(&head); break;
            case 3: return 0;
        }       
    }    
    return 0;
}

void PrintList(Item * head)
{
    Item temp;
    temp = *head;
    while(temp != NULL)
    {
        printf("%d %d\n", temp->x, temp->y);
        temp = temp->next;
    }
}

void AddEnd(Item * head)
{
    Item new, temp;
    new = (Item)malloc(sizeof(new));
    printf("Enter x and y: ");
    scanf("%d %d", &new->x, &new->y);
    new->next = NULL;
    if(*head == NULL)
    {
        *head = new;
    }
    else
    {
        temp = *head;
        while(temp != NULL)
        {
            temp = temp->next;
        }

        temp = new;
    }

}

我刚试过的这段代码也不起作用:

void AddEnd(Item * head, Item * item)
{
    Item new, temp;
    new = (Item)malloc(sizeof(new));
    printf("Enter x and y: ");
    scanf("%d %d", &new->x, &new->y);
    new->next = NULL;
    if(*head == NULL)
    {
        *head = new;
    }
    else
    {
        temp = *head;
        while(temp != NULL)
        {
            temp = temp->next;
        }

        temp = new;
        *item = temp;
    }
}

最佳答案

else 子句的 AddEnd 函数中,当您退出 while 循环时,temp 现在是 NULL。但是,它之前的元素仍然指向 NULL

尝试类似的东西

temp = *head;
if (temp->next == NULL) {
    temp->next = new;
} else {
    while((temp->next) != null) {
        temp = temp->next;
    }
    temp->next = new;
}

在您的 else 子句中。

(这个,以及你对其他人引用的 malloc 的理解的明显问题,new 应该是一个 Item * 并且 malloc 调用应该是 malloc(sizeof(Item))。你也不需要转换 malloc 的返回值(事实上,如果你这样做,会发生一些陷阱)。 阅读你的 typedefs a更仔细一点,new 应该 实际上是一个 Item(因为它是一个指向 List 结构的指针,并且您有typedef List* Item).尝试使用 new = malloc(sizeof(List)); 并将 new 声明为 List * 类型。 (typedef List * Item 使您的代码难以阅读;它变得不太清楚什么是指针,什么不是。)

关于无法将项目添加到链接列表的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18028047/

相关文章:

c - 如何正确解决指针对齐增加的问题?

c - 通过引用将 Unsigned Long Long 传递给 pthread_create

c - 如何限制用户输入?

c - 错误: initializer element is not constant - linux driver

c - C 语言的多线程 TCP 服务器崩溃

c - 如何获取硬链接(hard link)数量最少的文件?

c - 如何检查一个点是否在点簇内

c - 如何使用 C 中先前定义的常量来定义静态常量?

c - 如果同一个共享库工作正常,为什么静态库会导致对齐问题?

c - 在 BST 中找到给定总和的一对