Reputation: 327
I am trying to build a linked list, with the elements at a certain depth
I came up with this:
void nivel(ABin a, int k, SList *l, int level){
if (!a) return;
if(k == level){
SList n = (SList)malloc(sizeof(struct slist));
n->value = a->value;
n->next=(*l);
(*l) = n;
return;
}else{
nivel(a->left, k, l, level+1);
nivel(a->right, k, l, level+1);
}
}
It does work
But the exercise asks to use this header: SList nivel (ABin a, int n)
I have tried with a void to practice. But can't figure out how to make the one that returns the linked lists.
Data from structure and binary tree:
typedef struct slist
{
int value;
struct slist* next;
} *SList;
typedef struct arvbin* ABin;
typedef struct arvbin
{
int value;
ABin right;
ABin left;
} arvb;
EDIT:
<---------------working with header in the exercise-----------> // A thank you to Politank-Z
SList nivel_(ABin a, int k){
SList *l;
nivel(a, k, l, 1);
return l;
}
void nivel(ABin a, int k, SList *l, int level){
if (!a) return;
if(k == level){
SList n = (SList)malloc(sizeof(struct slist));
n->value = a->value;
n->next=(*l);
(*l) = n;
return;
}else{
nivel(a->left, k, l, level+1);
nivel(a->right, k, l, level+1);
}
}
Upvotes: 1
Views: 156
Reputation: 3729
Regarding your difficulty with the prototype: it is fairly common to be restricted to a function prototype which doesn't meet the needs of your implementation. In such cases, it is often easier to call your function from the prototyped function then to shoehorn your functionality into the prototype.
Upvotes: 1
Reputation: 366
} *SList;
will create a pointer type called SList. This causes confusion within your code, because you use SList *l
which is a pointer to a pointer! Change your struct typedef to just } SList
. This way you don't have to dereference a pointer of a pointer to reach the pointer value.
Upvotes: 0
Reputation: 11
Do you mean that you want to build a linked list using binary tree? However, you may add a new item into your list when (k == level), then you call nivel(a->left, k, l, level+1). It won't add any node here, because k != level+1 now, so your list will contain just one node actually...
BTW, you should ensure nivel add one node into your list everytime.
Upvotes: 1