简体   繁体   中英

How do you insert an array of numbers in to a linked list?

I have an assignment to make a program that gets 14 scores, and putting them into a doubly linked list, so that i can sort the data, but I notice that you can't insert an array of numbers into a linked list, per se

int scores[15]

into a linked list.

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
#include<windows.h>
#include<conio.h>

struct mhs{

    char name[30];
    int scores[15];
    int finalScore;

    struct mhs *next, *prev;

};

void data(struct mhs **head, struct mhs **node, struct mhs **tail){

    char nama[30];
    int scores[15];
    int finalScore;
    int i, sum = 0;

    system("cls");
    printf("Name: ");
    scanf("[^\n]", name);
    fflush(stdin);
    for(i = 0; i < 14 ; i++){
        printf("Score %d: ", i+1);
        scanf("%d", &scores[i]);
    }
    for(i = 13; i > 3; i--){
        sum = sum + scores[i];
    }
    printf("Final Score: %d\n", sum / 10);
    system("pause");
    (*node) = (struct mhs*) malloc(sizeof(struct mhs));
    strcpy((*node)->nama, nama);
    (*node)->scores= scores;                      //here's where I insert the scores
    (*node)->finalScore= finalScore;

    if(*head == NULL){
        *head = *node;
        *tail = *node;
    } else {
        (*tail)->next = *node;
        (*node)->prev = *tail;
        *tail = *node;
    }

}

void data is a function from int main(), that's why the struct is using a pointer. Can anyone tell me how to add an array of numbers into a linked list?

            tldr;
            Did you said to insert each array of elements in to a single node of linked list.
            Then you need to assign base address of array to the node of the linked list to create linked list with each node containing array elements.

            It would be like -
        node 1 - array1 elements like [1,2,3,4]
        node 2 - array2 elements like [6,4,2,4]
        ...

            If you just want to convert linked list by using array elements. Then just iterate over it.
            Like

for(int i = 0;i<array_size;i++)
p->next = a[i];
p->next = NULL

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