#include #include #include typedef struct _node List; /* the name if the list will be a pointer to a node, so alias List type to Node */ typedef struct _node Node; struct _node { Node *next; char *name; int age; }; /* to create a new node with a name and an age */ Node* create(char *name, int age){ Node* anode = (Node*) malloc(sizeof(Node)); anode->name = (char*) malloc(sizeof(char) * (strlen(name)+1)); /* need one extra space for the null character */ strcpy(anode->name, name); anode->age = age; anode->next = NULL; return anode; /* memory dynamically allocated in subroutines is not released after exiting the function */ } /* to destroy an node */ void destroy(Node *anode){ free(anode->name); free(anode); } /* to insert a node */ void insert(List* list, char* name, int age){ Node* p = list; Node* anode = create(name, age); while (p->next && (strcmp(anode->name, p->next->name)>0)) p = p->next; anode->next = p->next; p->next = anode; } /* to search a name */ Node* search(List *list, char *name){ Node* p = list; while (p->next && (strcmp(name, p->next->name)>0)) p = p->next; if (p->next && !strcmp(name, p->next->name)) return p->next; else return NULL; } /* to delete a node */ int delete(List *list, char* name){ Node *q, *p = list; while (p->next && (strcmp(name, p->next->name)>0)) p = p->next; if (p->next && !strcmp(name, p->next->name)) { q = p->next; p->next = p->next->next; destroy(q); return 1; } else return 0; } /* to kill the whole list */ void kill(List *list){ Node *q, *p=list; while (p->next){ q = p; p = p->next; destroy(q); } destroy(p); } /* show a node */ void printnode(Node* anode){ printf("%s is %d years old.\n", anode->name, anode->age); } /* show the whole list */ void printall(List* list){ Node* p = list; while (p->next) { printnode(p->next); p = p->next; } } /* print a task selection menu */ int tasksel(){ char ch=0; while (ch < '0' || ch > '4') { printf("\nPlease select a task:\n"); printf(" 1. Add a person\n"); printf(" 2. Delete a person\n"); printf(" 3. Search a person\n"); printf(" 4. Show the whole pool\n"); printf(" 0. Exit\n"); ch = getchar(); } return ch-'0'; } main(){ List *pool = create("",0); /* the header node is empty for easy programing */ int task; char name[20]; int age; Node *anode; while (task = tasksel()) { switch (task) { case 1: printf("Name? "); scanf("%s",name); printf("Age? "); scanf("%d",&age); insert(pool, name, age); printf("Inserted\n"); break; case 2: printf("Name to delete? "); scanf("%s",name); if (delete(pool, name)) printf("%s is deleted.\n",name); else printf("%s is not on file.\n"); break; case 3: printf("Name to search? "); scanf("%s", name); if (anode = search(pool, name)) printnode(anode); else printf("Not found.\n"); break; case 4: printall(pool); } } kill(pool); }