在 C 中打印队列时丢失元素

Losing elements while printing a queue in C

这是我的代码:

typedef struct noeud{
    int x;
    struct noeud* suivant;
} noeud;

typedef noeud* file;

file enfiler(file f, int val){
    file nv = (file) malloc(sizeof(noeud));
    nv->x = val; nv->suivant = NULL;

    if (f == NULL)
      f = nv;
    else {
      file tmp = f;
      while(tmp->suivant != NULL) tmp = tmp->suivant;
      tmp->suivant = nv;
    }
    return f;
}

file defiler(file f){//removing an element of the FIFO data structure
  if (f == NULL)
    return f;
  else {
    file tmp = f;
    f = f->suivant;//receiving address of next node, the last one points to NULL
    free(tmp);
    return f;
  }
}

int tete(file f){
  return f->x;//getting the element of the head
}

void init(file * f) {
  *f = NULL;
}

void affiche(file f){//print data structure's elements
  if (f == NULL)
    printf("File vide.\n");
  else {//emptying the FIFO data structure into tmp to access elements
    file tmp; init(&tmp);
    while(f != NULL){
        tmp = enfiler(tmp, tete(f));
        f = defiler(f);
    }
    int i = 0;
    while(tmp != NULL) {//emptying tmp to original f
        printf("F[%d] = %d\n", ++i, tete(tmp));
        f = enfiler(f, tete(tmp));
        tmp = defiler(tmp);
    }
  }
}

这是我的输入:

file f; init(&f);//initializing f to NULL
f = enfiler(f, 6);//adding elements
f = enfiler(f, 45); 
f = enfiler(f, 78);
f = enfiler(f, 5);
affiche(f);
affiche(f);
affiche(f);

这是输出:

F[1] = 6
F[2] = 45
F[3] = 78
F[4] = 5
F[1] = 78
F[2] = 5
F[1] = 2036736 //this is a random value

void affiche(file f)两个头都丢了,我修改了函数file defiler(file f)但是好像找不到错误,file enfiler(file f, int x)也可以。

感谢您的宝贵时间!

为了反转输出,您构建并重新构建了队列。您的重构不会重新link相同的节点。相反,您只需获取这些值并创建两个全新的列表。这意味着afficher中的局部变量f通常在进入afficher之后和离开之前是不同的。您可以通过添加以下语句来测试它:

void affiche(noeud *f)
{
    printf("entree: %p\n", f);

    // body of afficher function    

    printf("sortie: %p\n", f);
}

问题是您的调用函数中的 f 没有更新。它可能指向最近释放的内存或另一个有效节点。换句话说,您的列表可能已损坏。

解决这个问题的最简单方法是返回新头,如 enfilerdefiler