1. 程式人生 > >C Primer Plus 17_1 | 修改程式清單17.2,使其既能以正序又能以逆序顯示電影列表。一種方法是修改連結串列定義以使連結串列能被雙向遍歷;另一種方法是使用遞迴

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;
}      

執行結果: