Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.32 KB | None | 0 0
  1. /*
  2.  * This procedure adds a contact into a contacts list
  3.  * @ls:     The contacts list
  4.  * @name:   Name of the contact
  5.  * @num:    Phone number of the contact
  6.  */
  7. void
  8. add_to_list(struct node **ls, char *name, char *num)
  9. {
  10.     struct node *p      = NULL;
  11.     struct node *crt    = NULL;
  12.     struct node *prev   = NULL;
  13.     int comp        = 0;
  14.  
  15.     p = malloc(sizeof(struct node));
  16.  
  17.     if (p == NULL){
  18.         perror("Error allocating memory ");
  19.         exit(-1);
  20.     }
  21.  
  22.     p->firstname = name;
  23.     p->telnum = num;
  24.     p->next = NULL;
  25.  
  26.     /* We put a capital as first letter of the firstname */
  27.     p->firstname[0] = toupper(p->firstname[0]);
  28.  
  29.     /* We check if the list contains no contact */
  30.     if (*ls == NULL){
  31.         *ls = p;
  32.     } else{
  33.         crt = *ls;
  34.         prev    = *ls;
  35.  
  36.         while (crt != NULL){
  37.             comp = strcmp(p->firstname,crt->firstname);
  38.             if (comp < 0){
  39.                 /*
  40.                  * We check if the new element is before
  41.                  * the head of the list
  42.                  */
  43.                 if (crt == *ls){
  44.                     *ls = p;
  45.                     (*ls)->next = prev;
  46.                 } else{
  47.                     prev->next = p;
  48.                     p->next = crt;
  49.                 }
  50.  
  51.                 break;
  52.             } else if (comp == 0){
  53.                 /* If contact already exists */
  54.                 (void)printf("\nContact already exists!\n");
  55.                 break;
  56.             }
  57.  
  58.             /* We check if we are at the tail of the list */
  59.             if (crt->next == NULL){
  60.                 crt->next = p;
  61.                 break;
  62.             }
  63.  
  64.             prev = crt;
  65.             crt = crt->next;
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement