Page 39 - DCAP605_ADVANCED_DATA_STRUCTURE_AND_ALGORITHMS
P. 39

Advanced Data Structure and Algorithms




                    Notes


                                      Lab Exercise   Program

                                     # include <stdio.h>
                                        # include <stdlib.h>
                                        int length ( struct node * );
                                        struct node
                                        {
                                           int data;
                                           struct node *link;
                                        };
                                        /* a function which appends a new node to an existing list used for
                                     building a list */
                                        struct node *insert(struct node *p, int n)
                                        {
                                           struct node *temp;
                                           if(p==NULL)
                                           {
                                               p=(struct node *)malloc(sizeof(struct node));
                                              if(p==NULL)
                                              {
                                                      printf(“Error\n”);
                                                 exit(0);
                                              }
                                              p-> data = n;
                                              p-> link = NULL;
                                           }
                                           else
                                           {
                                              temp = p;
                                              while (temp-> link != NULL)
                                                     temp = temp-> link;
                                              temp-> link = (struct node *)malloc(sizeof(struct node));
                                             if(temp -> link == NULL)
                                              {
                                                      printf(“Error\n”);
                                                 exit(0);
                                              }
                                              temp = temp-> link;






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