X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=TP_8%2Fexo3%2Fexo3.c;fp=TP_8%2Fexo3%2Fexo3.c;h=18b065181cf5b65c6467b5e9c584ea65a5e2fe78;hb=7c4bfcc0aacab351b7534e2e09ebd98239901db0;hp=0000000000000000000000000000000000000000;hpb=731a470e947f3c7fcd9012cd7982cf2488f57381;p=TD_C.git diff --git a/TP_8/exo3/exo3.c b/TP_8/exo3/exo3.c new file mode 100644 index 0000000..18b0651 --- /dev/null +++ b/TP_8/exo3/exo3.c @@ -0,0 +1,74 @@ +#include +#include + +/** Display a prompt to the user then wait for an integer input. */ +int promptValue(const char* prompt) { + printf("%s:\n", prompt); + int result; + scanf("%d", &result); + return result; +} + +/** Linked list of int */ +typedef struct link_s { + int value; + struct link_s* next; +} link_t; + +link_t* list_new(int value) { + link_t* link_t_new; + link_t_new = malloc(sizeof(link_t)); + link_t_new->value = value; + link_t_new->next = NULL; + return link_t_new; +} + +void list_append(link_t* head, int value) { + + while (head->next != NULL) { + head = head->next; + } + head->next = list_new(value); +} + +unsigned list_count(link_t* head) { + // And if head is not defined? + int count = 1; + + while (head->next != NULL) { + ++count; + head = head->next; + } + return count; +} + +int list_get(link_t* head, unsigned index) { + + if (index < list_count(head)) { + for (int i = 0; i < index; i++) { + head = head->next; + } + return head->value; + } else { + return -1; + } +} + +void list_clear(link_t* link) { + free(link); +} + +int main() { + link_t* head = list_new(1); + printf("Longueur de la liste: %d\n", list_count(head)); + list_append(head, 2); + list_append(head, 3); + list_append(head, 4); + printf("Longueur de la liste: %d\n", list_count(head)); + 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; +}