hello guys, i read someone else's code which works. then i wrote this one myself to see if i can incorporate recursion in adding nodes to a linked list structure. in the debugger after the loop ought to end, it revives itself, assigns value 1 to num_m and starts all over again so irrespective of num_m, length() always return 2. this is beyond my comprehension. I've been on this for 3hrs and no luck
Code:
#include <stdio.h>
#include <stdlib.h>
struct node{
int a;
struct node *next;
};
int add_node(struct node **head, int val, int num_m);
int length(struct node *);
int main(){
struct node *head = NULL;
struct node first;
first.a = 5;
first.next = NULL;
head = &first;
printf("%p", &first);
add_node(&head, 5, 2);
int count = length(head);
printf("lenght is %d", count);
}
int add_node(struct node **head, int val, int num_m){
int i;
int x = 0;
x = num_m;
struct node *new_node;
struct node *temp;
while(x > 0){
new_node = (struct node *)malloc(sizeof(struct node));
new_node->a = val;
new_node->next = NULL;
(*head)->next = new_node;
x--;
if (x > 0){
i = val+2;
add_node(&new_node, i, x);
}
}
}
int length(struct node *head){
if(head->next == NULL)
return 1;
else{
return (1 + length(head->next));
}
}