简体   繁体   中英

Malloc linked-list in c

I'm new to C. I need to create a linked-list in c using malloc, I'm supposed to create my solution within struct list* solution(). Given A list of numbers I need them to display until the int -1 is given. After creating linked list, return a pointer to the root node of the linked list.So far I can only get one number to appear after the program has been executed.

#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);
    }
}

I expect the output to be 2 6 4 7 8 2 9 but so far Am only able to produce the output of just 2 or just 9.

You should not be allocating an array. When creating a linked list, you allocate one list node each time through the loop.

You need two variables -- head is a pointer to the first node in the list, the listpointer is pointer to the last element, where we want to append the next node.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM