リスト

なんかなにも整理されてないけどとりあえず。特にfindあたりがひどい。つかinsertもひどいか。。deleteもひどいな。つか全部ひどいか。。。まあなんつーかそうだよねーってかんじだけど。。あーなんだかなー。まあなんていうかポインタあたりの復習にはなってるからとりあえずはよし。整理とかはあとでする。

抽象化ってどうしたらいいんだ。もうちょい先人のプログラム読んで勉強しろってことかこれ。

#include <stdio.h>
#include <stdlib.h>

typedef struct list {
    int data;
    struct list *next_ptr;
} List;

void list_insert(List *, int);
void list_insert_after(List *, int, int);
void list_delete(List *, int);
List * list_find(List *, int);
int list_is_tail(List *item);
void list_print_all(List *item);


int main()
{
    List head = { 
        0,  
        NULL
    };  
    List *list_tmp;

    list_insert(&head, 1); 
    list_insert(&head, 4); 
    list_insert(&head, 2); 

    list_tmp = list_find(&head, 1); 
    if (list_tmp != NULL)
        printf("1 found.\n");

    list_tmp = list_find(&head, 2); 
    if (list_tmp != NULL)
        printf("2 found.\n");

    list_print_all(&head);
    list_delete(&head, 4); 
    list_delete(&head, 5); 
    list_print_all(&head);
    list_insert(&head, 4); 
    list_print_all(&head);
    list_insert_after(&head, 4, 2); 
    list_insert_after(&head, 8, 0); 
    list_delete(&head, 4); 
    list_print_all(&head);

    return 0;
}


void list_insert(List *item, int data)
{
    List *tmp;

    while (!list_is_tail(item))
        item = item->next_ptr;

    tmp = (List *)malloc(sizeof(List));
    tmp->data = data;
    tmp->next_ptr = NULL;

    item->next_ptr = tmp;
}

void list_insert_after(List *item, int data, int after)
{
    List *new, *found;

    found = list_find(item, after);

    if (found == NULL) {
        list_insert(item, data);
    }
    else {
        new = (List *)malloc(sizeof(List));
        new->data = data;
        new->next_ptr = found->next_ptr;
        found->next_ptr = new;
    }
}

void list_delete(List *item, int data) {
    List *found, *prev;

    found = item;
    while(found != NULL) {
        if (found->data == data)
            break;
        prev = found;
        found = found->next_ptr;
    }

    if (found != NULL) {
        prev->next_ptr = found->next_ptr;
        free(found);
    }
}


List * list_find(List *item, int data) {
    List *current = item;

    while(current != NULL) {
        if (current->data == data)
            break;

        current = current->next_ptr;
    }

    return current;
}

int list_is_tail(List *item)
{
    if (item->next_ptr == NULL) {
        return 1;
    }
    else {
        return 0;
    }
}

void list_print_all(List *item)
{
    printf("%d -> ", item->data);
    if (!list_is_tail(item)) {
        list_print_all(item->next_ptr);
    }
    else {
        printf(" End of List.\n");
    }
}


Out:

1 found.
2 found.
0 -> 1 -> 4 -> 2 ->  End of List.
0 -> 1 -> 2 ->  End of List.
0 -> 1 -> 2 -> 4 ->  End of List.
0 -> 8 -> 1 -> 2 -> 4 ->  End of List.