Page 48 - DCAP605_ADVANCED_DATA_STRUCTURE_AND_ALGORITHMS
P. 48

Unit 2: Linked Lists




                                                                                                Notes


           Lab Exercise    Program: Here is a program for building and printing the elements of the
                         circular linked list.
             # include <stdio.h>
             # include <stdlib.h>
             struct node
             {
                int data;
                struct node *link;
             };
             struct node *insert(struct node *p, int n)
             {
                struct node *temp;
                /* if the existing list is empty then insert a new node as the
             starting node */
                    if(p==NULL)
                    {
                      p=(struct node *)malloc(sizeof(struct node)); /* creates new
             node data value passes
                as parameter */
                     if(p==NULL)
                     {
                              printf(“Error\n”);
                              exit(0);
                      }
                      p-> data = n;
                       p-> link = p; /* makes the pointer pointing to itself because it
             is a circular list*/
                   }
                   else
                   {
                      temp = p;
                /* traverses the existing list to get the pointer to the last node of
             it */
                      while (temp-> link != p)
                             temp = temp-> link;
                      temp-> link = (struct node *)malloc(sizeof(struct node)); /*
             creates new node using
                      data value passes as
                      parameter and puts its
                      address in the link field
                      of last node of the
                      existing list*/




                                           LOVELY PROFESSIONAL UNIVERSITY                                    43
   43   44   45   46   47   48   49   50   51   52   53