Displays the movie list both in the original order and in reverse order using Linked List - C Data Structure

C examples for Data Structure:Linked List

Description

Displays the movie list both in the original order and in reverse order using Linked List

Demo Code

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

#define TSIZE 45/*w w  w  . ja va 2 s  .co  m*/

typedef struct film 
{
  char title[TSIZE];
  int rating;
  struct film * next;
} Film;

typedef Film * List;

void delete_list(List * list);

void add_film(List filmlist, Film * item);

void list_films(List filmlist);

void reverse_list_films(List filmlist);

void delete_list(List * list_ptr){
  Film * tmp, * list = *list_ptr;
  while (list != NULL){
    tmp = list->next;
    free(list);
    list = tmp;
  }

  *list_ptr = NULL;
}

void add_film(List filmlist, Film * new_film)
{
  Film * film_ptr = filmlist;
  while (film_ptr->next != NULL)
    film_ptr = film_ptr->next;
  film_ptr->next = new_film;
}

void list_films(List film_ptr){
  while (film_ptr != NULL){
    printf("%s: %d\n", film_ptr->title, film_ptr->rating);
    film_ptr = film_ptr->next;
  }
}
void reverse_list_films(List film_ptr){
  if (film_ptr == NULL)
    return;
  else{
    reverse_list_films(film_ptr->next);
    printf("%s: %d\n", film_ptr->title, film_ptr->rating);
  }
}

char * get(char * string, int n);

int main(void)
{
  List film_list = NULL;
  Film * current;
  char input[TSIZE];

  puts("Enter first movie title:");
  while (get(input, TSIZE) != NULL && input[0] != '\0'){
    current = (Film *) malloc(sizeof(Film));
    if (current == NULL){
      fprintf(stderr, "Could not allocate memory.\n");
      exit(EXIT_FAILURE);
    }

    current->next = NULL;
    strcpy(current->title, input);
    printf("Enter your rating (0 - 10): ");
    scanf("%d", &(current->rating));
    while (getchar() != '\n') continue;

    if (film_list == NULL)
      film_list = current;
    else
      add_film(film_list, current);

    puts("Enter next movie title (empty line to stop):");
  }

  list_films(film_list);
  puts("");

  reverse_list_films(film_list);

  delete_list(&film_list);

}

char * get(char * string, int n){
  // wrapper for fgets that replaces first newline with null
  char *return_value = fgets(string, n, stdin);
  while (*string != '\0'){
    if (*string == '\n'){
      *string = '\0';
      break;
    }
    string++;
  }
  return return_value;
}

Result


Related Tutorials