#include #include #include typedef struct node { int val; struct node *next; } NODE; NODE *init_node(int val) { NODE *buf; buf = malloc(sizeof(NODE)); if (buf == NULL) { fprintf(stderr, "Error allocating node\n"); return NULL; } buf->val = val; buf->next = NULL; return buf; } void add_node(NODE *list, int val) { NODE *node = init_node(val); if (node == NULL) { return; } for (; list->next != NULL; list = list->next); list->next = node; } void del_node(NODE *list, NODE *node) { for (; list->next != NULL; list = list->next) { if (list->next == node) { list->next = (list->next)->next; free(node); return; } } } int count_length(NODE *list) { int counter = 1; for (; list->next != NULL; list = list->next) { counter++; } return counter; } void print_list(NODE *list) { for (; list->next != NULL; list = list->next) { printf("%d\n", list->val); } printf("%d\n", list->val); } NODE *reverse_list(NODE *list) { NODE *prev = NULL; NODE *next = list->next; while (next != NULL) { list->next = prev; prev = list; list = next; next = list->next; } list->next = prev; return list; } void delete_list(NODE* list) { if(list -> next == NULL) { free(list); return; } NODE* next_node = list -> next; while (next_node != NULL) { free(list); list = next_node; next_node = list -> next; } free(list); return; } NODE* list_remove_all(NODE *list, int val) { NODE* head = list; NODE* buf; while (head != NULL && head->val == val) { buf = head->next; free(head); head = buf; } if (head == NULL) return head; list = head; while (list->next != NULL) { if (list->next->val == val) { while(list->next != NULL && list->next->val == val) { buf = list->next; list->next = list->next->next; free(buf); } } else list = list->next; } return head; } int main() { NODE *list = init_node(4); add_node(list, 5); print_list(list); printf("\n[%d]\n\n", count_length(list)); del_node(list, list->next); print_list(list); printf("\n[%d]\n\n", count_length(list)); add_node(list, 1); add_node(list, 2); add_node(list, 3); add_node(list, 4); add_node(list, 3); add_node(list, 3); add_node(list, 1); print_list(list); printf("\n[%d]\n\n", count_length(list)); list = reverse_list(list); print_list(list); printf("\n[%d]\n\n", count_length(list)); list = list_remove_all(list, 1); print_list(list); printf("\n[%d]\n\n", count_length(list)); delete_list(list); return 0; }