From: Jérôme Benoit Date: Wed, 1 Mar 2017 18:52:17 +0000 (+0100) Subject: TP 9 exo2: Add list_insert and list_delete linked list helpers X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=0d650b413a907f0fd4e78ee1500c196e9fd41d9f;p=TD_C.git TP 9 exo2: Add list_insert and list_delete linked list helpers functions. Signed-off-by: Jérôme Benoit --- diff --git a/TP_9/exo2/clist.c b/TP_9/exo2/clist.c index 0ee532f..0aa9e37 100644 --- a/TP_9/exo2/clist.c +++ b/TP_9/exo2/clist.c @@ -31,6 +31,47 @@ link_t* list_prepend(link_t* head, int value) { return first_link; } +link_t* list_insert(link_t* head, unsigned index, int value) { + link_t* link_insrt = list_new(value); + link_t* head_first = head; + //link_t* head_prev = NULL; + link_t* head_next = NULL; + + for (unsigned i = 0; i < index; i++) { + head = head->next; + } + //head_prev = head; + head->next = link_insrt; + head_next = head->next; + head = link_insrt; + head->next = head_next; + return head_first; +} + +link_t* list_delete(link_t* head, unsigned index) { + link_t* head_first = head; + link_t* head_prev = NULL; + link_t* head_next = NULL; + + if (index == 0) { + head_next = head->next; + free(head); + head = head_next; + return head; + } else { + for (unsigned i = 0; i < index-1; i++) { + head = head->next; + } + head_prev = head; + head = head->next; + head_next = head->next; + free(head); + head = head_prev; + head->next = head_next; + return head_first; + } +} + unsigned list_count(link_t* head) { int count = 0; diff --git a/TP_9/exo2/clist.h b/TP_9/exo2/clist.h index ec1c13a..40eaef1 100644 --- a/TP_9/exo2/clist.h +++ b/TP_9/exo2/clist.h @@ -10,6 +10,8 @@ typedef struct link_s { link_t* list_new(int value); link_t* list_append(link_t* head, int value); link_t* list_prepend(link_t* head, int value); +link_t* list_insert(link_t* head, unsigned index, int value); +link_t* list_delete(link_t* head, unsigned index); unsigned list_count(link_t* head); void list_set(link_t* head, unsigned index, int value); int list_get(link_t* head, unsigned index); diff --git a/TP_9/exo2/exo2.c b/TP_9/exo2/exo2.c index 15172ce..ff5912b 100644 --- a/TP_9/exo2/exo2.c +++ b/TP_9/exo2/exo2.c @@ -20,6 +20,16 @@ int main() { printf("Valeur a index %d: %d\n", 4, list_get(head, 4)); list_set(head, 0, 78); printf("Valeur a index %d: %d\n", 0, list_get(head, 0)); + printf("Valeur a index %d: %d\n", 1, list_get(head, 1)); + printf("Valeur a index %d: %d\n", 2, list_get(head, 2)); + head = list_insert(head, 2, 7); + printf("Valeur a index %d: %d\n", 1, list_get(head, 1)); + printf("Valeur a index %d: %d\n", 2, list_get(head, 2)); + printf("Valeur a index %d: %d\n", 3, list_get(head, 3)); + //head = list_delete(head, 2); + printf("Valeur a index %d: %d\n", 2, list_get(head, 2)); + printf("Valeur a index %d: %d\n", 3, list_get(head, 3)); + printf("Valeur a index %d: %d\n", 4, list_get(head, 4)); list_clear(head); return 0;