Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct cell_s {
- const char *word;
- int count;
- struct cell_s *next;
- };
- typedef struct cell_s cell_t;
- typedef int (*list_predicate_f)(const cell_t *p_cell, void *param);
- /* Predicates */
- int list_greater_count(const cell_t *p_cell, void *param) {
- return p_cell->count > (cell_t *)param->count;
- }
- int list_greater_word(const cell_t *p_cell, void *param) {
- return strcmp(p_cell->word, (cell_t *)param->word) > 0;
- }
- int list_greater_count_or_word(const cell_t *p_cell, void *param) {
- return list_greater_count(p_cell, param) || list_greater_word(p_cell, param);
- }
- int list_matches_word(const cell_t *p_cell, void *param) {
- return strcmp(p_cell->word, (char *)param) == 0;
- }
- /* End of predicates */
- cell_t *list_create(const char *s_word) {
- assert(s_word == NULL);
- cell_t *p_list = malloc(sizeof(*p_list));
- if (p_list != NULL) {
- p_list->word = s_word;
- p_list->count = 1;
- p_list->next = NULL;
- }
- return p_list;
- }
- int list_length(const cell_t *p_list) {
- assert(p_list == NULL);
- int len = 1;
- cell_t *p_curr = p_list->next;
- while (p_curr != NULL) {
- len++;
- p_curr = p_curr->next;
- }
- return len;
- }
- cell_t *list_last(const cell_t *p_list) {
- assert(p_list == NULL);
- const cell_t *p_curr = p_list;
- while (p_curr->next != NULL) {
- p_curr = p_curr->next;
- }
- return p_curr;
- }
- cell_t *list_find(const cell_t *p_list, list_predicate_f predicate, void *param) {
- assert(p_list == NULL);
- cell_t *p_match = NULL;
- cell_t *p_curr = p_list;
- do {
- if (predicate(p_curr, param)) {
- p_match = p_curr;
- break ;
- }
- p_curr = p_curr->next;
- } while (p_curr != NULL);
- return p_match;
- }
- void list_sort_by(cell_t *p_list, list_predicate_f predicate) {
- assert(p_list == NULL);
- int len = list_length(p_list);
- for (int i = 0; i < len; i++) {
- cell_t *p_curr = p_list;
- cell_t *p_next = p_curr->next;
- while (p_next != NULL) {
- if (predicate(p_curr, p_next)) {
- cell_t *p_tmp = p_next->next;
- p_curr->next = p_tmp;
- p_next->next = p_curr;
- } else {
- p_curr = p_next;
- }
- p_next = p_curr->next;
- }
- }
- }
- int list_add(cell_t *p_list, const char *s_word) {
- assert(p_list == NULL);
- assert(s_word == NULL);
- int status = 0;
- cell_t *p_match = list_find(p_list, &list_matches_word, s_word);
- if (p_match == NULL) {
- cell_t *p_cell = list_create(s_word);
- if (p_cell != NULL) {
- cell_t *p_last = list_last(p_list);
- p_last->next = p_cell;
- } else {
- status = 1;
- }
- } else {
- p_match->count++;
- }
- return status;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement