gpt4 book ai didi

c - 如何将保存矩阵固定到链表中

转载 作者:太空宇宙 更新时间:2023-11-04 07:48:15 25 4
gpt4 key购买 nike

我想将矩阵添加到链表中,例如: exemple但是我的代码无法保存矩阵,打印矩阵时,全为0

我的代码:

void construcMat(matrice_creuse *m, int t[N][M], size_t Nlign, size_t Ncol) {
m->Ncolonnes = Ncol;
m->Nlignes = Nlign;
m->liste = malloc(Nlign * sizeof(liste_ligne));
for(size_t i = 0; i < Nlign; i++) {
m->liste[i] = NULL;
element* dernier = m->liste[i];
for (size_t j = 0; j < Ncol; j++) {
if (t[i][j] != 0) {
element* e = malloc(sizeof(element));
e->col = j;
e->val = t[i][j];
e->suiv = NULL;
if (dernier != NULL)
dernier->suiv = e;
else // Sinon
dernier = e;
dernier = dernier->suiv;
}
}
}
}

主要代码:

int mat[4][5] = {{0, 1, 0, 2, 0}, {0, 0, 0, 5, 4}, {1, 0, 0, 0, 5}, {0, 0, 0, 0, 0}};
matrice_creuse m1;
construcMat(&m1, mat, 4, 5);

最佳答案

您仍然必须将列表放在m->liste[i] 中。你可以用双指针来做到这一点;见下文:

void construcMat(matrice_creuse *m, int t[N][M], size_t Nlign, size_t Ncol) {
m->Ncolonnes = Ncol;
m->Nlignes = Nlign;
m->liste = malloc(Nlign * sizeof(liste_ligne));
for(size_t i = 0; i < Nlign; i++) {
m->liste[i] = NULL;
element **dernier = &m->liste[i]; // use a double indirection
for (size_t j = 0; j < Ncol; j++) {
if (t[i][j] != 0) {
element* e = malloc(sizeof(element));
e->col = j;
e->val = t[i][j];
e->suiv = NULL;

*dernier= e; // assign it..
dernier= &e->suiv; //..and advance
}
}
}
}

关于c - 如何将保存矩阵固定到链表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55569865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com