1. 程式人生 > 實用技巧 >實驗9-8 通訊錄排序

實驗9-8 通訊錄排序

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 typedef struct node
 6 {
 7     char name[11];
 8     char birthday[9];
 9     char phone[18];
10     struct node *next;
11 } NODE, *LINK;
12 void AddNewNode(LINK head, int n);
13 void PrintList(LINK head);
14
void cleanList(LINK head); 15 int main(void) 16 { 17 int n; 18 LINK head; 19 20 head = (LINK)malloc(sizeof(NODE)); 21 head->next = NULL; 22 23 scanf("%d", &n); 24 AddNewNode(head, n); 25 PrintList(head); 26 cleanList(head); 27 28 return 0; 29 } 30 void AddNewNode(LINK head, int
n) 31 { 32 LINK tail = head; 33 LINK p, q, newNode; 34 35 for (int i = 0; i < n; i++) 36 { 37 newNode = (LINK)malloc(sizeof(NODE)); 38 scanf("%s %s %s", newNode->name, newNode->birthday, newNode->phone); 39 newNode->next = NULL; 40 if (i == 0
) 41 { 42 tail->next = newNode; 43 tail = newNode; 44 } 45 else 46 { 47 q = head; 48 p = head->next; 49 while (p != NULL) 50 { 51 if (strcmp(newNode->birthday, p->birthday) < 0) 52 { 53 q->next = newNode; 54 newNode->next = p; 55 break; 56 } 57 else 58 { 59 q = p; 60 p = p->next; 61 } 62 } 63 if (p == NULL) 64 { 65 q->next = newNode; 66 } 67 } 68 } 69 } 70 void PrintList(LINK head) 71 { 72 LINK p = head->next; 73 74 while (p != NULL) 75 { 76 printf("%s %s %s\n", p->name, p->birthday, p->phone); 77 p = p->next; 78 } 79 } 80 void cleanList(LINK head) 81 { 82 LINK p; 83 84 while (head != NULL) 85 { 86 p = head->next; 87 free(head); 88 head = p; 89 } 90 }