view stacks_lists/remove_list_duplicates/solution.c @ 2:6bebf4b42ebc

Correctly format the stacks and lists exercices
author Louis Opter <kalessin@kalessin.fr>
date Mon, 01 Jul 2013 23:25:58 -0700
parents stacks_lists/remove_list_duplicates/remove_duplicates.c@20fea762903e
children
line wrap: on
line source

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

struct list
{
    struct list *next;
    struct list *prev;
    int         value;
};

void
print(struct list *head)
{
    for (; head; head = head->next)
        printf("%d ", head->value);
    printf("\n");
};

void
insert(struct list **head, int value)
{
    struct list *node = malloc(sizeof(*node));
    node->prev = NULL;
    node->next = *head;
    node->value = value;
    if (*head)
        (*head)->prev = node;
    *head = node;
}

struct list *
remove_node(struct list *node)
{
    assert(node);
    node->prev->next = node->next;
    if (node->next)
        node->next->prev = node->prev;
    struct list *next = node->next;
    free(node);
    return next;
}

void
remove_duplicates(struct list *head)
{
    for (struct list *target = head; target; target = target->next) {
        for (struct list *it = target->next; it;) {
            if (it->value == target->value) {
                it = remove_node(it);
            } else {
                it = it->next;
            }
        }
    }
}

int
main(void)
{
    struct list *head = NULL;

    for (int i = 5; i != 0; i--)
        insert(&head, i);
    for (int i = 1; i <= 5; i++)
        insert(&head, i);
    
    print(head);
    remove_duplicates(head);
    print(head);

    return EXIT_SUCCESS;
}