Pregunta

I have the following code:

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;

}

How can I add a new node in a circular list in which the sentinel already allocated? It has bugged me for hours, since the nodes are allocated but the links are borked, it shows me the same data value for each, except the sentinel, which is fine.

What I tried:

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

The struct:

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

LE: So I updated the code, and wrote this to check it: /* TL2 u*/

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

Yes, the info is void, but I was curious if the cells were different...I suppose no:

  2686632 2686632 2686632 2686632 2686632 2686632  

What is going on here?!

¿Fue útil?

Solución

Your code should be

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;

This inserts h in between the p and the sentinel

Otros consejos

maybe my understanding is flawed, but I believe this should be:

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

This essentially makes a circular list. Assuming p is the first node in the circular list and h is the last node.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top