标签:
单向链表:
见 书 C primer plus (488 程序 17.2)
1 #include <stdio.h> 2 #include <stdlib.h> /* has the malloc prototype */ 3 #include <string.h> /* has the strcpy prototype */ 4 #define TSIZE 45 /* size of array to hold title */ 5 6 struct film { 7 char title[TSIZE]; // 书名 8 int rating; // 评分 9 struct film * next; // 指向链表的下一个结构 10 }; 11 12 13 14 int main(void) 15 { 16 struct film * head = NULL; // 头指针 17 struct film * prev, * current; // 前指针 当前指针 18 char input[TSIZE]; 19 20 /* Gather and store information */ //收集并保存信息 21 puts("Enter first movie title:"); 22 23 24 while (gets(input) != NULL && input[0] != ‘\0‘) // input 0x12ff44 存放书名 great expections 25 { 26 current = (struct film *) malloc(sizeof(struct film)); // ¤t=0x0012ff74 current=0x00431d70 第二次 current=0x431d00 27 if (head == NULL) /* first structure */ 28 head = current; // 把 current 指向的地址 传给 head指针,那么 head=0x00431d70 29 else /* subsequent structures */ 30 prev->next = current; // prev->next=0x431d00 31 32 current->next = NULL; // 表示当前结构是列表中的最后一个 33 strcpy(current->title, input); // ¤t->title=0x00431d70 "great exception " current->title= 0x00431d70 34 puts("Enter your rating <0-10>:"); 35 36 scanf("%d", ¤t->rating); // ¤t->rating=0x00431da0 "8" current->rating= 8 37 38 39 while(getchar() != ‘\n‘) 40 continue; 41 puts("Enter next movie title (empty line to stop):"); 42 prev = current; // &prev = 0x0012ff78 prev=0x00431d70 43 44 } 45 46 47 /* Show list of movies */ 48 if (head == NULL) 49 printf("No data entered. "); 50 else 51 printf ("Here is the movie list:\n"); 52 53 current = head; // ¤t=0x0012ff74 current=0x00431d70 也就是 开始 54 while (current != NULL) 55 { 56 printf("Movie: %s Rating: %d\n", 57 current->title, current->rating); 58 current = current->next; // 指向下一个指针 59 } 60 61 current=head; // 从开头指针 开始释放。 62 while(current != NULL) 63 { 64 free(current); 65 current=current->next; 66 67 } 68 printf("Bye !\n"); 69 70 71 return 0; 72 73 }
标签:
原文地址:http://www.cnblogs.com/shengruxiahua/p/4902505.html