Linked list insertion using recursion
//list.h file
typedef struct _lnode{
struct _lnode *next;
unsigned short row;
unsigned short column;
short data;
}lnode;
typedef struct _llist{
struct _lnode *head;
unsigned int size;
}llist;
//list.c file
void add(llist *list, lnode *newNode){
list->size++;
addRecursion(&list->head, newNode);
}
lnode* addRecursion(lnode **node, lnode *newNode){
if(*node == NULL){
*node = newNode;
}
else{
lnode *nextNode = *node->next;
*node->next = addRecursion(&nextNode, newNode);
}
return node;
}
//main function
开发者_JAVA技巧llist list;
list.head = NULL;
lnode* new_node;
new_node = make_node(1,1,2);
add(&list, new_node);
printList(list.head);
I think I have a problem in addRecursion function especially in "else" statement.. I am getting confused since I started using double pointers... How can I fix this?
First replace *node->next
with (*node)->next
as ->
has higher priority than *
.
Also in addRecursion
replace return node
with return *node
as node
is double pointer and you return an ordinary one.
calling addrecursion?? in else. seems to call itself infinitely;
first you set the newNode->next to point to the head (node). and you need to modify the head to point to the new node.
which your code doesn't do, cause it's using a copy of the address contained in head.
Your nextNode
is local, so &
on it gives the address of a local variable on stack. Instead you need to pass &node->next
, and the return value is irrelevant then (as in the first call in add
, where you discard the return value).
精彩评论