Arnab_Manna

length of a linked list using recirsion

Jun 10th, 2020
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.56 KB | None | 0 0
  1. //c program to find the length of a linked list using recirsion
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<conio.h>
  5.  
  6. typedef struct node
  7. {
  8.     int data;
  9.     struct node *link;
  10. }NODE;
  11.  
  12. NODE *getnode()
  13. {
  14.     NODE *New;
  15.     New=(NODE *)malloc(sizeof(NODE));
  16.     New->link=NULL;
  17.     return New;
  18. }
  19. NODE *insert(NODE *Start, int x)
  20. {
  21.     NODE *New=getnode(),*Last;
  22.     if(New==NULL)
  23.     {
  24.         printf("\nNo space");
  25.         return Start;
  26.     }
  27.     New->data = x;
  28.     if(Start==NULL)
  29.     {
  30.         Start=New;
  31.         return Start;
  32.     }
  33.     Last = Start;
  34.     while(Last->link != NULL)
  35.     {
  36.         Last = Last->link;
  37.     }
  38.     Last->link = New;
  39.     return Start;
  40. }
  41. void display(NODE *Start)
  42. {
  43.     if(Start==NULL)return;
  44.     printf("%d ",Start->data);
  45.     display(Start=Start->link);
  46.     //printf("%d ",Start->Data);
  47. }
  48.  
  49. NODE *CreateList()
  50. {
  51.     char Resp;
  52.     int x;
  53.     NODE *Start=NULL;
  54.     while(1)
  55.     {
  56.         printf("\nAny more data to insert(Y/N)?");
  57.         Resp=getche();
  58.         if(Resp=='N' || Resp=='n')
  59.         {
  60.             return Start ;
  61.         }
  62.         printf("\nEnter Data:");
  63.         scanf("%d",&x);
  64.         Start=insert(Start,x);
  65.         display(Start);
  66.     }
  67. }
  68. int l=0;
  69. //recursive function to find length
  70. int length(NODE *temp)  
  71. {
  72.     if(temp==NULL)
  73.         return l;
  74.     else
  75.     {
  76.         l=l+1;
  77.         length(temp->link);
  78.     }
  79. }
  80.  
  81. main()
  82. {
  83.     NODE *start;
  84.     int len;
  85.     start=CreateList();
  86.     //printf("The number of nodes are: %d\n", length(start));
  87.     len=length(start);
  88.     printf("The list has a total of %d no of nodes",l);
  89. }
Add Comment
Please, Sign In to add comment