For clarity, I put all the bizarre logic into a function (which could be inlined)
#include <stdio.h>
struct list {
struct list *prev;
struct list *next;
int val;
};
struct list arr[] =
{ {arr+1, arr+2, 1}
, {arr+3, arr+4, 2}
, {arr+5, arr+6, 3}
, {arr+3, arr+4, 4}
, {arr+3, arr+5, 5}
, {arr+4, arr+6, 6}
, {arr+5, arr+6, 7}
};
int is_leaf(struct list *p)
{
if (p->prev == p) return 1; // 4
if (p->next == p) return 1; // 7
if (p->next->prev == p) return 1; // 5,6
return 0; // non-leaves : 1,2,3
}
unsigned recurse (struct list *p)
{
int chk;
unsigned ret=1;
chk = is_leaf(p) ;
if (!chk) ret+=recurse(p->prev);
printf("%d %s\n", p->val, chk ? "leaf" : "nonLeaf" );
if (!chk) ret+=recurse(p->next);
return ret;
}
int main (void) {
unsigned cnt;
cnt = recurse (arr);
printf( "Result=%u\n", cnt );
return 0;
}
Output:
4 leaf
2 nonLeaf
5 leaf
1 nonLeaf
6 leaf
3 nonLeaf
7 leaf
Result=7