Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * This procedure adds a contact into a contacts list
- * @ls: The contacts list
- * @name: Name of the contact
- * @num: Phone number of the contact
- */
- void
- add_to_list(struct node **ls, char *name, char *num)
- {
- struct node *p = NULL;
- struct node *crt = NULL;
- struct node *prev = NULL;
- int comp = 0;
- p = malloc(sizeof(struct node));
- if (p == NULL){
- perror("Error allocating memory ");
- exit(-1);
- }
- p->firstname = name;
- p->telnum = num;
- p->next = NULL;
- /* We put a capital as first letter of the firstname */
- p->firstname[0] = toupper(p->firstname[0]);
- /* We check if the list contains no contact */
- if (*ls == NULL){
- *ls = p;
- } else{
- crt = *ls;
- prev = *ls;
- while (crt != NULL){
- comp = strcmp(p->firstname,crt->firstname);
- if (comp < 0){
- /*
- * We check if the new element is before
- * the head of the list
- */
- if (crt == *ls){
- *ls = p;
- (*ls)->next = prev;
- } else{
- prev->next = p;
- p->next = crt;
- }
- break;
- } else if (comp == 0){
- /* If contact already exists */
- (void)printf("\nContact already exists!\n");
- break;
- }
- /* We check if we are at the tail of the list */
- if (crt->next == NULL){
- crt->next = p;
- break;
- }
- prev = crt;
- crt = crt->next;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement