Created
November 23, 2010 08:39
-
-
Save erenon/711469 to your computer and use it in GitHub Desktop.
book list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
typedef struct _book { | |
char author[50]; | |
int page; | |
int is_sentinel; | |
struct _book *next; | |
struct _book *prev; | |
} book; | |
int count_pages(book *head, char *author) { | |
head = head->next; | |
int sum = 0; | |
while (head->is_sentinel == 0) { | |
if ( strcmp(head->author, author) == 0) { | |
sum += head->page; | |
} | |
head = head->next; | |
} | |
return sum; | |
} | |
/*TEST ONLY*/ | |
book *create_book(char author[50], int page) { | |
book *item; | |
item = (book *)malloc(sizeof(book)); | |
if (item == NULL) { exit(1); } | |
strcpy(item->author, author); | |
item->page = page; | |
item->is_sentinel = 0; | |
return item; | |
} | |
/*TEST ONLY*/ | |
book *create_book_list() { | |
book *head, *tail; | |
head = create_book("", 0); | |
tail = create_book("", 0); | |
head->is_sentinel = 1; | |
tail->is_sentinel = 1; | |
head->prev = NULL; | |
head->next = tail; | |
tail->prev = head; | |
tail->next = NULL; | |
return head; | |
} | |
/*TEST ONLY*/ | |
void append_book(book *head, book *item) { | |
while(head->next->is_sentinel == 0) { | |
head = head->next; | |
} | |
item->next = head->next; | |
head->next->prev = item; | |
head->next = item; | |
item->prev = head; | |
} | |
/*TEST ONLY*/ | |
void delete_book_list(book *head) { | |
book *next; | |
while(head) { | |
next = head->next; | |
free(head); | |
head = next; | |
} | |
} | |
/*TEST ONLY*/ | |
int main() { | |
book *head = create_book_list(); | |
append_book(head, create_book("foo", 5)); | |
append_book(head, create_book("bar", 10)); | |
append_book(head, create_book("baz", 8)); | |
append_book(head, create_book("foo", 24)); | |
append_book(head, create_book("foo", 1)); | |
printf("%d\n", count_pages(head, "foo")); | |
delete_book_list(head); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment