0
//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
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?

5
  • It would be helpful if you were to explain (1) what you hoped your code would do, (2) what it actually does, and (3) why you aren't happy with #2 (if that isn't immediately obvious). Commented Mar 24, 2011 at 22:58
  • first of all list isn't NULL initialized and inside addRecursion you do *node == NULL. Commented Mar 24, 2011 at 22:58
  • Also: If this is homework, you should say so. (If it looks like homework and you don't say whether it is, some people will avoid answering for fear of doing your homework for you.) Commented Mar 24, 2011 at 23:00
  • No it is no hw. I normally use java or c# reference based language. I just wanted to practice myself for future job interviews.. Commented Mar 24, 2011 at 23:05
  • I am expecting insert a new node into the linked list recursively.. and addRecursion function is not working now.. Commented Mar 24, 2011 at 23:06

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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).

1 Comment

I replaced addRecursion(&nextNode, newNode); to addRecursion(&node->next, newNode);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.