Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef struct Contact{
- struct Contact* next; /*next is used to navigate through structures.*/
- char* name;
- char* tel;
- }Contact;
- Contact*start; /* start always points to the first node of the linked list.*/
- /*Defining of the functions to be implemented*/
- Contact* goEnd()
- {
- Contact* end = start;
- while(end->next != NULL)
- {
- end = end->next;
- }
- return end;
- }
- void addFirst(Contact* new_contact )
- {
- if(start == NULL)
- {
- start = new_contact;
- start->next = NULL;
- }
- else
- {
- Contact* current = start;
- start = new_contact;
- start->next = current;
- }
- }
- void addLast(Contact* new_contact)
- {
- if(start == NULL){
- start = new_contact;
- }
- else
- {
- goEnd()->next = new_contact;
- }
- new_contact->next = NULL;
- }
- void removeByName(char*name)
- {
- Contact* sel = start;
- Contact** prevNext = &start;
- while(sel != NULL){
- if(sel->name == name)
- {
- *prevNext = sel->next; /*to delete the contact and free the memory occupied*/
- free(sel);
- return;
- }
- else
- {
- prevNext = &sel->next;
- sel = sel->next;
- }
- }
- }
- void removeFirst()
- {
- if(start != NULL){
- Contact* ers = start;
- start = start->next;
- free(ers);
- }
- }
- void removeLast()
- {
- Contact* head = start;
- Contact** prevNext = &start;
- if(start != NULL){
- while(head->next != NULL){
- prevNext = &head->next;
- head = head->next;
- }
- free(head);
- *prevNext = NULL;
- }
- }
- void printList() /*Prints out the contact lists*/
- {
- Contact* current = start;
- while(current != NULL)
- {
- printf("The Name is: %s - %s\n", current->name, current->tel);
- current = current->next;
- }
- printf("\n\n");
- }
- void builtList(Contact contacts[])
- {
- Contact *ptr=NULL;
- int i;
- for(i=0; i<=6; i++)
- {
- ptr=&contacts[i];
- addLast(ptr);
- }
- }
- /*Implementation methods*/
- int main()
- {
- Contact contacts[7]=
- {
- {NULL,"Dennis","0203/123456"},
- {NULL,"Chantal","0177/3123345"},
- {NULL,"Robert","0163/9295986"},
- {NULL,"Bjoern","040 - 123232345"},
- {NULL,"Andreas","+49 178 11903123"},
- {NULL,"Jenny","+41 119 34544345"},
- {NULL,"Zeuss","0162-123-4531698"},
- };
- builtList(contacts);
- printList();
- printf("Removing name Andreas\n");
- removeByName("Andreas");
- printList();
- printf("Removing first\n");
- removeFirst();
- printList();
- printf("Removing last\n");
- removeLast();
- printList();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement