Scanning numbers in link list using recursion

Problem statement
Write a c program to recursively add element in a link list
your program should also print them recursively
#include<stdio.h>
#include<stdlib.h>
struct node{
  int data;
  struct node * next;
};
struct node* scan(int n);
void print(struct node *head);
void add(struct node* head,int toadd);
int main()
{
  struct node *head;
  int n;
  head=NULL;
  printf("enter number of elements in the link list ");
  scanf("%d",&n);
  head=scan(n);
  printf("the elements entered by you is ");
  print(head->next);
  return 0;
}
void print(struct node *head)
{
  if(head!=NULL)
    {
      printf("%d ",head->data);
      print(head->next);
    }
  return ;
}
struct node* scan(int n)
{
  int i,temp;
  struct node *head;
  head=(struct node *)malloc(sizeof(struct node));
  head->next=NULL;
  head->data=0;
  for(i=0;i<n;i++)
    {
      scanf("%d",&temp);
      add(head,temp);
    }
  return head;
}
void add(struct node* head,int toadd)
{
  struct node *newnode;
  if(head->next!=NULL)
    {
      add(head->next,toadd);
    }
  else
    {
      newnode=(struct node *)malloc(sizeof(struct node));
      newnode->data=toadd;
      head->next=newnode;
      newnode->next=NULL;
      return ; 
    }

No comments:

Post a Comment