【问题标题】:How do you insert an array of numbers in to a linked list?如何将一组数字插入到链表中?
【发布时间】:2023-03-19 14:37:01
【问题描述】:

我有一个任务要编写一个获得 14 分的程序,并将它们放入一个双向链表中,以便我可以对数据进行排序,但我注意到您不能将数字数组插入到链表中, 本身

int scores[15]

进入一个链表。

#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 是来自 int main() 的函数,这就是结构使用指针的原因。 谁能告诉我如何将一组数字添加到链表中?

【问题讨论】:

  • 这个函数声明 void data(struct mhs **head, struct mhs **node, struct mhs **curr, struct mhs **tail) 没有意义。例如函数中没有使用参数struct mhs **curr。
  • scores 是一个 int 变量,但您可以像使用数组一样使用它 scores[i]
  • @VladfromMoscow 对不起,是的,函数中没有使用 **curr,我正准备使用 **curr 打印数据
  • @Ackdari 抱歉,我的代码缺少一些东西,我试图声明 int 分数[15]
  • 你知道如何在链表中插入一个数吗?你知道如何遍历数组吗?

标签: c linked-list doubly-linked-list


【解决方案1】:
            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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2021-01-09
    相关资源
    最近更新 更多