- #include "stdafx.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <windows.h>
- #define TSIZE 45
-
- struct film
- {
- char title[TSIZE];
- int rating;
- struct film * next;
- };
-
- int _tmain(int argc, _TCHAR* argv[])
- {
- struct film *head=NULL;
- struct film *prev, *current;
- char input[TSIZE];
- puts("Enter first movie title:");
- while (gets(input) != NULL&&input[0] != '\0')
- {
- current = (struct film*) malloc(sizeof(struct film));
- if (head == NULL)
- head = current;
- else
- {
- prev->next = current;
- }
-
- current->next = NULL;
- strcpy(current->title, input);
- puts("Enter your rating <0-10>:");
- scanf_s("%d", ¤tt->rating);
- while (getchar() != '\n')
- continue;
- puts("Enter next movie title(empty line to stop):");
- prev = current;
-
- }
- if (head == NULL)
- printf("No data entered.");
- else
- printf("Here is the movie list :\n");
- current = head;
- while (current != NULL)
- {
- printf("Movie : %s rating: %d \n", current->title, current->rating);
- current = current->next;
- }
-
- current = head;
- while ((current!=NULL))
- {
- free(current);
- current = current->next;
- }
- printf("Bye\n");
- system("pause");
- return 0;
- }
课本源码,但是在释放内存的时候出错了。最后一个while()写法有问题正在求证中。
本例的关键点:
1.结构体的定义
- struct film
- {
- char title[TSIZE];
- int rating;
- struct film * next;
- };
关系到里面的数据类型,next链接到下一个数据
需要申请空间,用于进入的数据放到内存中,head是表头,用prev和current来表示整个链表,prev是前一个结构体,current是当前jieg,当前的结构体中需要有数据,此时将现在的结构体的next赋值为NULL(以后遍历的时候,只需要一个while !NULL 从表头遍历到尾部)
- while (gets(input) != NULL&&input[0] != '\0')
- {
- current = (struct film*) malloc(sizeof(struct film));
- if (head == NULL)
- head = current;
- else
- {
- prev->next = current;
- }
-
- current->next = NULL;
- strcpy(current->title, input);
- puts("Enter your rating <0-10>:");
- scanf_s("%d", ¤tt->rating);
- while (getchar() != '\n')
- continue;
- puts("Enter next movie title(empty line to stop):");
- prev = current;
-
- }
一下的片段是遍历链表
- if (head == NULL)
- printf("No data entered.");
- else
- printf("Here is the movie list :\n");
- current = head;
- while (current != NULL)
- {
- printf("Movie : %s rating: %d \n", current->title, current->rating);
- current = current->next;
- }
找到表头,然后进行遍历
最后
- current = head;
- while ((current!=NULL))
- {
- free(current);
- current = current->next;
- if(current=NULL) break;
- }
释放内存的时候出错了,正在求解,