1 #include <stdio.h> 2 #include <stdlib.h> 3 4 struct Book 5 { 6 char title [128]; 7 char author [40]; 8 struct Book *next; 9 }; 10 11 void getInput(struct Book *book) 12 { 13 printf("请输入书名:"); 14 scanf("%s",book->title); 15 printf("请输入作者:"); 16 scanf("%s",book->author); 17 //book->next = NULL; 18 } 19 20 21 22 //因为返回值是void类型的 所以要修改头指针指向的地址,就要传入头指针的地址 23 void addBook(struct Book **plibrary) 24 { 25 struct Book *book,*temp; 26 book = (struct Book *)malloc(sizeof(struct Book)); 27 if(book ==NULL) 28 { 29 printf("动态申请内存失败"); 30 exit(1); 31 } 32 33 getInput(book); 34 if(*plibrary!=NULL) 35 { 36 37 //这里是尾插法 38 temp= *library; 39 //定位单链表的尾部位置 40 while(temp->next!=NULL) 41 { 42 temp = temp->next; 43 } 44 //插入数据 45 temp->next = book; 46 book->next = NULL; 47 48 /*这里是头插法 49 temp = *plibrary; 50 *plibrary = book; 51 book->next = temp;*/ 52 53 } 54 else 55 { 56 *plibrary = book; 57 book->next = NULL; 58 59 } 60 book->next = NULL; 61 } 62 void printLibrary(struct Book *library) 63 { 64 struct Book *book; 65 int count = 1; 66 book = library; 67 while(book!=null) 68 { 69 printf("Book%d:",cout); 70 printf("书名:",book->title); 71 printf("作者",author); 72 count++; 73 book = book->next; 74 75 } 76 } 77 void releaseLibrary(struct Book *library) 78 { 79 while(library!=NULL) 80 { 81 free(library); 82 library = library->next; 83 //要先取到next 再清空 84 } 85 } 86 int main(void) 87 { 88 struct Book *library = NULL; 89 int ch; 90 91 while(1) 92 { 93 printf("请问是否需要录入书籍信息 (Y/N):"); 94 do 95 { 96 ch=getchar(); 97 }while(ch!='Y'&&ch!='N'); 98 if(ch =='Y') 99 { 100 addBook(&library); 101 } 102 else 103 { 104 break; 105 } 106 } 107 printf("请问是否需要打印图书馆信息(Y/N):"); 108 do 109 { 110 ch=getchar(); 111 }while(ch!='Y'&&ch!='N'); 112 if(ch =='Y') 113 { 114 printLibrary(library); 115 } 116 reaseLibrary(library); 117 118 119 return 0; 120 }