开发者

Stop condition for printing linked structs?

I have the following struct:

struct cell {
    int nmbr;
    st开发者_高级运维ruct cell *p;
};

I have created a chain of linked structs from this type. Every struct is connected to its predecessor through *p. If I decide to print all nmbrs with a recursive algorithm as shown below, how do I define the stop condition?

void write(struct cell* l) {
    /* The following if statement doesn't solve my problem,
       but hopefully you see what I'm trying to do */
    if (&l != 0x000000) {
        printf("%d \t", l->nmbr);
        write(l->p);
    }
}


You want

if (l != 0)

or

if (l != NULL)

Of course, you also need to make sure that the tail of your linked list has p assigned NULL as well; otherwise it will be uninitialized and probably something not NULL but invalid anyway.


You should check against 'l' not being NULL rather than '&l' assuming that the linked list in NULL terminated.


Assuming the linked list is not cyclic, you just stop when you reach a null pointer. Change

if (&l != 0x000000)

to

if (l != NULL)


As others have said, you should check l (el), not &l, against 0 or NULL. So, your function should look something like:

void write(CELL* l) {
    if (l != 0x000000) {
        printf("%d \t", l->nmbr);
        write(l->p);
    }
}

That said, it is easy to accomplish the same thing using a while, thus avoiding the overhead of recursion:

  list_pos = list_head;
  while (list_pos != NULL) {
    printf("%d \t", list_pos->nmbr);
    list_pos = list_pos -> p;
  }


the print number up here, for the current node.

if(l->p!=NULL)
write(l->p);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜