gpt4 book ai didi

c - 在循环列表中添加节点

转载 作者:太空宇宙 更新时间:2023-11-04 02:57:35 24 4
gpt4 key购买 nike

我有以下代码:

int InsForward (TL2 p, void* x){
/* Inserta a node a step forward from the supplied p*/
TL2 h = (TL2)calloc(1,sizeof(TCel2));
if (!h)
return 0;
h->pre = p->pre;
h->nxt= p;
p->pre = h;
p->pre->nxt = h;
h->info = x;
return 1;

如何在已分配哨兵的循环列表中添加新节点?它困扰了我好几个小时,因为节点已分配但链接已中断,它向我显示了每个节点的相同数据值,除了哨兵,这很好。

我尝试过的:

 /* TCel a, int p, FILE fi*/
while(fscanf(fi,"%i%i", &(p.x), &(p.y)) == 2)
if ( InsForward(a, &p) == 0)
break;

结构:

 typedef struct cel2
{
struct cel2 *pre, *nxt;
void* info;
} TCel2, *TL2;

LE:所以我更新了代码,并写了这个来检查它: /* TL2 u*/

for (u = a->nxt; u != a; u = u->nxt)
printf("%i %i\n", u->info, u->info);

是的,信息无效,但我很好奇细胞是否不同......我想不是:

  2686632 2686632 2686632 2686632 2686632 2686632  

这是怎么回事?!

最佳答案

你的代码应该是

int InsForward (TL2 p, void* x){
/* Inserta a node a step forward from the supplied p*/
TL2 h = (TL2)calloc(1,sizeof(TCel2));
if (!h)
return 0;
h->pre = p; //sets h previous to point to p
h->nxt= p->nxt; //sets h next to point to where p was pointing ( sentinel )
p->nxt->prv = h; //sets the sentinel previous to point to h
p->nxt = h; //sets the p next to point to h
h->info = x;
return 1;

这会在 p 和哨兵之间插入 h

关于c - 在循环列表中添加节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15710650/

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