aboutsummaryrefslogtreecommitdiff
path: root/semestre 3/structures des données/td/td2/exo1.c
blob: 752828a52070fdeb9e882615086032bf9676cdf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <stdlib.h>
#include <stdio.h>
#include "LDC.h"

Cell* creerElement(int val){
    Cell* cell = (Cell*) malloc(sizeof(Cell));
    cell->val = val;
    cell->after = NULL;
    cell->before = NULL;
    return cell;
}

ChainedList* initialiserListe(ChainedList* list){
    list->first = NULL;
    list->last = NULL;
    return list;
}

ChainedList* creerListe(){
    ChainedList* list = (ChainedList*) malloc(sizeof(ChainedList));
    return initialiserListe(list);
}

int listeVide(ChainedList* list){
    /* we assume in this case that first is equal to last */
    return !list->first;
}

void insererEnTete(ChainedList* list, int val){
    Cell* cell = creerElement(val);
    cell->after = list->first;
    if (listeVide(list)){
        list->last = cell;
    } else {
        list->first->before = cell;
    }
    list->first = cell;
}

void insererEnFin(ChainedList* list, int val){
    Cell* cell = creerElement(val);
    cell->before = list->last;
    if (listeVide(list)){
        list->first = cell;
    } else {
        list->last->after = cell;
    }
    list->last = cell;
}

void afficher(ChainedList* list){
    Cell* cell = list->last;
    printf("[ ");
    while (cell){
        printf("%d ", cell->val);
        cell = cell->before;
    }
    printf("]\n");
}

ChainedList* rechercher(ChainedList* list, int val){
    Cell* cell = list->last;
    while (cell){
        if (cell->val == val){
            return list;
        }
        cell = cell->before;
    }
    return NULL;
}

void supprimerElement(ChainedList* list, Cell* el){
    if (listeVide(list)){
        return;
    }
    if (el == list->last){
        list->last = list->last->before;
        if (!list->last){
            list->first = NULL;
        }
        return;
    }
    if (el == list->first){
        list->first = list->first->after;
        if (!list->first){
            list->last = NULL;
        }
        return;
    }
    Cell* cell = list->last;
    while (cell && cell != el){
        cell = cell->before;
    }
    if (cell != el){
        return;
    }
    cell->before->after = cell->after;
    free(cell);
}

void supprimerTete(ChainedList* list){
    supprimerElement(list, list->first);
}

void supprimerFin(ChainedList* list){
    supprimerElement(list, list->last);
}

void desalloueListe(ChainedList* list){
    Cell* cell = list->last;
    while (cell){
        Cell* before = cell->before;
        free(cell);
        cell = before; 
    }
    free(list);
}