Hello,
I am trying to create a doubly linked list that will print the entered input in the original order and then print it in the reverse order.
Earlier I was able to get it to print the list twice, but the second time was not in the reverse order. Now it only prints the last element and I am not sure where the mistake is. Any help would be greatly appreciated as I have been trying to fix it for hours without success.
/*
Write a program so that it displays the movie list both in the original order and in reverse order. One approach is to modify the linked-list
definition so that the list can be traversed in both directions.
Another approach is to use recursion.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TSIZE 45
struct film {
char title[TSIZE];
int rating;
struct film* next ;
struct film* previous ;
} ;
int main(void) {
/* points to nextstruct in list */
struct film* head = NULL ;
struct film* prev ;
struct film* current ;
char input[TSIZE] ;
/* Gather and store information*/
puts("Enter first movie title:") ;
while (gets(input) != NULL && input[0] != '\0'){
current = malloc(sizeof(struct film)) ;
if (head == NULL) { /* first structure */
head = current;
}
else { /* subsequent structures */
current->previous = head ;
//prev->next = current ;
head->next = current ;
head = current ;
}
current->next = NULL ;
current->previous = NULL ;
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 ;
}
/* Show list of movies */
if (head == NULL) {
printf("No data entered. ") ;
}
else {
printf ("Here is the movie list:\n") ;
}
current = head ;
/* print in original order */
while (current != NULL) {
printf("1Movie: %s Rating: %d\n", current->title, current->rating) ;
current = current->next;
}
/* print in reverse order */
while (head != NULL) {
printf("2Movie: %s Rating: %d\n", head->title, head->rating);
head = head->previous;
}
/* free allocated memory */
current = head;
while (current != NULL) {
free(current);
current = current->next;
}
printf("Bye!\n");
return 0;
}