Page 40 - DCAP605_ADVANCED_DATA_STRUCTURE_AND_ALGORITHMS
P. 40

Unit 2: Linked Lists





                      temp-> data = n;                                                          Notes
                      temp-> link= NULL;
                   }
                   return (p);
                }
                /* a function which inserts a newly created node after the specified
             node */
                struct node * newinsert ( struct node *p, int node_no, int value )
                {
                   struct node *temp, * temp1;
                   int i;
                   if ( node_no <= 0 || node_no > length (p))
                   {
                           printf(“Error! the specified node does not exist\n”);
                      exit(0);
                   }
                   if ( node_no == 0)
                   {
                      temp = ( struct node * )malloc ( sizeof ( struct node ));
                      if ( temp == NULL )
                      {
                              printf( “ Cannot allocate \n”);
                              exit (0);
                      }
                      temp -> data = value;
                      temp -> link = p;
                      p = temp ;
                }
                else
                {
                    temp = p ;
                   i = 1;
                   while ( i < node_no )
                   {
                         i = i+1;
                         temp = temp-> link ;
                   }
                   temp1 = ( struct node * )malloc ( sizeof(struct node));
                   if ( temp == NULL )
                   {
                         printf (“Cannot allocate \n”);


                                           LOVELY PROFESSIONAL UNIVERSITY                                    35
   35   36   37   38   39   40   41   42   43   44   45