让程序既能正序也能逆序显示电影列表。使用双向链表
/让程序既能正序也能逆序显示电影列表。使用双向链表/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Movie
{
char title[100];
struct Movie *prev;
struct Movie *next;
} Movie;
typedef struct MovieList
{
Movie *head;
Movie *tail;
} MovieList;
void initMovieList(MovieList *list)
{
list->head = NULL;
list->tail = NULL;
}
void addMovie(MovieList *list, const char *title)
{
Movie *newMovie = (Movie *)malloc(sizeof(Movie));
strcpy(newMovie->title, title);
newMovie->prev = list->tail;
newMovie->next = NULL;
if (list->tail)
{
list->tail->next = newMovie;
}
else
{
list->head = newMovie;
}
list->tail = newMovie;
}
void displayMoviesForward(MovieList *list)
{
Movie *current = list->head;
printf("电影列表(正序):\n");
while (current)
{
printf("%s\n", current->title);
current = current->next;
}
}
void displayMoviesBackward(MovieList *list)
{
Movie *current = list->tail;
printf("电影列表(逆序):\n");
while (current)
{
printf("%s\n", current->title);
current = current->prev;
}
}
void freeMovieList(MovieList *list)
{
Movie *current = list->head;
while (current)
{
Movie *temp = current;
current = current->next;
free(temp);
}
}
int main()
{
MovieList movieList;
initMovieList(&movieList);
int choice;
char title[100];
do
{
printf("1. 添加电影\n");
printf("2. 显示电影(正序)\n");
printf("3. 显示电影(逆序)\n");
printf("0. 退出\n");
printf("请选择操作: ");
scanf("%d", &choice);
getchar();
switch (choice)
{
case 1:
printf("请输入电影名称: ");
fgets(title, sizeof(title), stdin);
title[strcspn(title, "\n")] = 0;
addMovie(&movieList, title);
break;
case 2:
displayMoviesForward(&movieList);
break;
case 3:
displayMoviesBackward(&movieList);
break;
case 0:
printf("退出程序。\n");
break;
default:
printf("无效选择,请重新输入。\n");
break;
}
} while (choice != 0);
freeMovieList(&movieList);
return 0;
}