c - c中的malloc链表

标签 c linked-list dynamic-memory-allocation

我是 C 新手。我需要使用 malloc 在 c 中创建一个链接列表,我应该在 struct list* Solution() 中创建我的解决方案。给定一个数字列表,我需要它们显示,直到给出 int -1 为止。创建链表后,返回一个指向链表根节点的指针。到目前为止,我只能在程序执行后得到一个数字。

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

typedef struct list{
    int value;
    struct list *next;
} List ;

struct list* solution()
{
    int n = 0, a;
    List *listpointer;
    List *listpointer2;
    listpointer = ( List* ) malloc( 200 * sizeof(List*));
    listpointer2 = ( List* ) malloc( 200 * sizeof(List*));
    //for(n = 0; n < 7; n++)
    do   
    {
        scanf("%d", &a);
        if(a < 0)
        {
            listpointer[n].next = NULL;   
            break;
        }
        listpointer[n].value = a;
        listpointer[n].next = listpointer2[n].next;

        n++;
        //scanf("%d", &a);
        //listpointer2[n].value = a;
        //listpointer2[n].next = listpointer2[n].value;
    }while( a > 0);

    return listpointer;
}

int main()
{
    struct list *l=NULL,*temp;
    l = solution();
    if(l==NULL)
        printf("list is empty");
    else
    {
        do{
            printf("%d ",l->value);
            temp = l;
            l = l->next;
        }while(temp->next!=NULL);
    }
}

我预计输出为 2 6 4 7 8 2 9,但到目前为止我只能产生 2 或 9 的输出。

最佳答案

您不应该分配数组。创建链表时,每次循环都会分配一个链表节点。

您需要两个变量 - head 是指向列表中第一个节点的指针,listpointer 是指向最后一个元素的指针,我们要在其中追加下一个节点。

struct list* solution()
{
    int n = 0, a;
    List *listpointer = NULL;
    List *head = NULL;
    while(1)
    {
        scanf("%d", &a);
        if(a < 0)
        {
            break;
        }
        List *newNode = malloc(sizeof(List));
        newNode->value = a;
        newNode->next = NULL;
        if (listpointer) {
            listpointer->next = newNode;
            listpointer = newNode;
        } else {
            listpointer = newNode;
            head = newNode;
        }
    }

    return head;
}

关于c - c中的malloc链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56781541/

相关文章:

java - 如何编写一个junit测试来在操作之间插入双向链表?

python - Cython:如何将 python 对象作为 cython 类的属性

c - c 中的 strtok() - 段错误

c - 移动指针以便以不同的顺序打印

c++ - 在 C++11 中对齐内存的推荐方法是什么

c++ - 4 维 c++ 数组的动态内存分配以创建 HDF5 数据集

c - C中动态分配数组的数组

我可以将 IO 端口作为参数传递给函数吗?

c - 为什么程序有时会出现 "skip over"printfs?

c++ - 为什么在链接列表中链接之前需要填充数据?