Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- struct node {
- int value;
- struct node *next;
- };
- struct node *list_from_array(int *array, int length);
- void list_print(struct node *list);
- struct node *list_find(struct node **list, int value);
- void list_clear(struct node **list);
- void test_init(struct node **list);
- void test(struct node **list, int value);
- int main(void) {
- struct node *list_head;
- test_init(&list_head);
- test(&list_head, 11);
- test(&list_head, 1);
- test(&list_head, 12);
- test(&list_head, 10);
- test(&list_head, 9);
- test(&list_head, 13);
- test(&list_head, 9);
- test(&list_head, 7);
- test(&list_head, 14);
- test(&list_head, 1);
- test(&list_head, 4);
- test(&list_head, 15);
- list_clear(&list_head);
- return 0;
- }
- void test_init(struct node **list) {
- int init_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- *list = list_from_array(init_array, sizeof init_array / sizeof *init_array);
- list_print(*list);
- printf("\n");
- }
- void test(struct node **list, int value) {
- struct node *found = list_find(list, value);
- if(!found)
- printf("%d NO\n", value);
- else
- printf("%d OK\n", found->value);
- list_print(*list);
- printf("\n");
- }
- struct node *list_from_array(int *array, int length) {
- struct node *list = NULL;
- struct node **next_ptr = &list;
- for(int i = 0; i < length; i++) {
- struct node *new = malloc(sizeof *new);
- if(!new) {
- list_clear(&list);
- break;
- }
- new->value = array[i];
- /* *new = (struct node) {
- .value = array[i],
- .next = NULL,
- }; */
- *next_ptr = new;
- next_ptr = &new->next;
- }
- *next_ptr = NULL;
- return list;
- }
- void list_print(struct node *list) {
- if (!list) {
- printf("[]");
- return;
- }
- printf("[%d", list->value);
- list = list->next;
- while (list) {
- printf(", %d", list->value);
- list = list->next;
- }
- printf("]");
- }
- struct node *list_find(struct node **list, int value) {
- struct node **next_ptr = list;
- while(*next_ptr) {
- struct node *cur = *next_ptr;
- if (cur->value == value) {
- *next_ptr = cur->next;
- cur->next = *list;
- return *list = cur;
- }
- next_ptr = &cur->next;
- }
- return NULL;
- }
- void list_clear(struct node **list) {
- struct node *cur = *list;
- while(cur) {
- struct node *next = cur->next;
- free(cur);
- cur = next;
- }
- *list = NULL;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement