Hi, I have the code to add elements at the end of the linked list using recursion.
//Adds an element at end using recursion
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
void addatend(struct node **,int);
void display(struct node *);
int main()
{
struct node *p=NULL;
clrscr();
addatend(&p,14);
addatend(&p,20);
addatend(&p,31);
display(p);
getch();
return 0;
}
void addatend(struct node **ptr,int value)
{
if(*ptr==NULL)
{
*ptr=malloc(sizeof(struct node));
(*ptr)->data=value;
(*ptr)->link=NULL;
}
else
addatend(&((*ptr)->link),value);
}
void display(struct node *ptr)
{
struct node *q;
q=ptr;
while(q!=NULL)
{
printf("%d\t",q->data);
q=q->link;
}
}
I have just a small confusion, I think the pointer ptr should point to the last node after we add nodes at the end. But according to the program output, it points to the first node in the linked list. Please explain.