I wrote a recursive function to reverse a linked list as follows:
struct node{
int val;
struct node *next;
};
//Global pointer to structure
struct node *start=NULL,*head=NULL;
//*Function to input node*
void create(int data){
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
if(start == NULL){
temp->val=data;
temp->next=NULL;
start=temp;
head=temp;
}
else{
temp->val=data;
temp->next=NULL;
head->next=temp;
head=temp;
}
}
*Function to reverse the linked list*
void* rev(struct node *prev,struct node *cur){
if(cur!=NULL){
printf("Works");
rev(cur,cur->next);
cur->next=prev;
}
else{
start=prev;
}
}
And the related code in main is:
main(){
struct node *temp;
temp=start;
/*Code to insert values*/
rev(NULL,temp);
}
Now the code takes input and prints it perfectly, but after I call rev()
function the same traversal function prints nothing.
I did run the code on debugger line by line n it gave me the following output:
rev (prev=0x0, cur=0x0)
Also since cur
is somehow NULL, the if
part of rev()
never gets executed and only the else
executes once.
When I take input in my create()
function I do update start to the first element of the linked list and even in main a print statement proves it is so.
But then why the function rev()
always receives input parameters as NULL?
Please comment if any extra information is required.