I am new to C and I'm trying to learn more about pointers.
I have a working function that reverses a linked list recursively.
My working function looks like this:
Code:
/******************************************
* Parameters:
* - Reference pointer to head of list
* - Pointer to first node in list
******************************************/
void recursive_reverse(struct node **head_ptr, struct node *first)
{
struct node *dummy;
if(first->next == NULL)
return;
dummy = first->next;
first->next = dummy->next;
dummy->next = *head_ptr;
*head_ptr = dummy;
recursive_reverse(head_ptr, first);
}
node is
Code:
struct node
{
int data;
struct node *next;
};
My question is whether I can have a static pointer "first" (instead of the parameter "first") that gets initialised only once on the first itteration of the function and keeps track of where my original first node is?
When I try:
Code:
void recursive_reverse2(struct node **head_ptr)
{
static struct node *first = *head_ptr;
struct node *dummy;
if(first->next == NULL)
return;
dummy = first->next;
first->next = dummy->next;
dummy->next = *head_ptr;
*head_ptr = dummy;
recursive_reverse2(head_ptr);
}
I get the compiler error:
error: initializer element is not constant
I don't know enough about the language to understand why I can't do this and would really appreciate any guidance.
I'm sure there are other better ways to solve this specific problem but I would like to know if it's possible to adapt my solution with some kind of static pointer or if I'm wasting my time trying this route.
many thanks