C Primer Plus 17_1 | 修改程序清单17.2,使其既能以正序又能以逆序显示电影列表。一种方法是修改链表定义以使链表能被双向遍历;另一种方法是使用递归

思路:构造双向链表

#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",&current->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;
}      

运行结果:

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值