回复 6楼 TonyDeng
是的,受教了。。。
我刚刚用下面代码运行了一下,省去了没用到的函数,其余和书上例子基本相同(暂时不考虑释放内存等)
我一共输入了三次项目(一个项目包括电影名和评分)但是只显示了我第一次输入的项目,其余两项并没有显示
程序代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct film{
char title[45];
int rating;
}Item;
typedef struct node{
Item item;
struct node *next;
}Node;
typedef Node * List;
void Initialize(List *head);
int Additem(Item item, List *head);
void Traverse(const List *head);
int main(void)
{
List movies;
Item temple;
Initialize(&movies); //初始化
puts("Enter first movie title:");
while (gets(temple.title) != NULL&&temple.title[0] != '\0')
{
puts("Enter your rating<0-10>:\n");
scanf("%d", &temple.rating);
while (getchar() != '\n');
if (Additem(temple, &movies) == 0)
{
printf("Problem allocating memory.\n");
break;
}
puts("Enter next movie title:\n");
}
//显示
printf("Here is the movie list.\n");
Traverse(&movies);
while (getchar() != '\n');
getchar();
return 0;
}
void Initialize(List *head)
{
*head = NULL;
}
int Additem(Item item,List *head)
{
List nitem;
List current=*head;
nitem = (Node *)malloc(sizeof(Node));
if (nitem == NULL)
return 0;
nitem->item = item;
nitem->next = NULL;
if (current == NULL)
{
*head = nitem;
}
else
{
while (current != NULL)
{
current= current->next;
}
current = nitem;
}
return 1;
}
void Traverse(const List *head)
{
List pnode = *head;
while (pnode != NULL)
{
printf("title :%s ,rating:%d.\n", pnode->item.title, pnode->item.rating);
pnode = pnode->next;
}
}