【问题标题】:Adding nodes in a circular list在循环列表中添加节点
【发布时间】:2013-03-29 20:05:37
【问题描述】:

我有以下代码:

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  

这是怎么回事?!

【问题讨论】:

    标签: c list nodes circular-list


    【解决方案1】:

    你的代码应该是

    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

    【讨论】:

    • 谢谢,更新了我的帖子,链接现在似乎可以工作,但每个单元格中的信息都是一样的??
    • @SpaceNecron 您正在使用%i 而不是%p 打印指针。 urm 是什么?最好问一个新问题,而不是更新这个问题并弄得一团糟。
    【解决方案2】:

    也许我的理解有缺陷,但我认为应该是这样的:

    h->pre = p->nxt;
    p->nxt = h;
    h->nxt = p;
    

    这实质上是一个循环列表。假设 p 是循环链表中的第一个节点,h 是最后一个节点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      相关资源
      最近更新 更多