思路:构造双向链表
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define TSIZE 45
struct film{
char title[TSIZE];
int rating;
struct film * pre,* next; //指向链表的前一个结构,下一个结构
};
int main(void)
{
struct film *head=NULL,* end=NULL;
struct film * current,*prev,*temp;
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->pre=prev;}
current->next=NULL;
end=current;
strcpy(current->title,input);
puts("Enter your rating <0-10>:");
scanf("%d",¤t->rating);
while(getchar()!='\n')continue;
puts("Enter next movie title (empty line to stop):");
prev=current;
}
head->pre=NULL;
//给出电影列表正序
if(head==NULL)
printf("NO data enter.");
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;
}
//给出电影列表逆序
if(head==NULL)
printf("NO data enter.");
else printf("Here is the movie list :\n");
current=end;
while(current!=NULL)
{
printf("Movie: %s Rating: %d\n",current->title,current->rating);
current=current->pre;
}
//任务已完成,因此释放所分配的内存
current=head;
while(current!=NULL)
{
temp=current;
free(current);
current=temp->next;
}
printf("Bye!\n");
return 0;
}
运行结果: