BuildSystem: Even more sync to latest
[TD_C.git] / TP_8 / exo3 / exo3.c
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 /** Display a prompt to the user then wait for an integer input. */
5 int promptValue(const char* prompt) {
6 printf("%s:\n", prompt);
7 int result;
8 scanf("%d", &result);
9 return result;
10 }
11
12 /** Linked list of int */
13 typedef struct link_s {
14 int value;
15 struct link_s* next;
16 } link_t;
17
18 link_t* list_new(int value) {
19 link_t* link_t_new;
20 link_t_new = malloc(sizeof(link_t));
21 link_t_new->value = value;
22 link_t_new->next = NULL;
23 return link_t_new;
24 }
25
26 void list_append(link_t* head, int value) {
27
28 while (head->next != NULL) {
29 head = head->next;
30 }
31 head->next = list_new(value);
32 }
33
34 unsigned list_count(link_t* head) {
35 // And if head is not defined?
36 int count = 1;
37
38 while (head->next != NULL) {
39 ++count;
40 head = head->next;
41 }
42 return count;
43 }
44
45 int list_get(link_t* head, unsigned index) {
46
47 if (index < list_count(head)) {
48 for (unsigned i = 0; i < index; i++) {
49 head = head->next;
50 }
51 return head->value;
52 } else {
53 return -1;
54 }
55 }
56
57 void list_clear(link_t* link) {
58
59 while (link != NULL) {
60 link_t* next_link = link->next;
61 free(link);
62 link = next_link;
63 }
64 }
65
66 int main() {
67 link_t* head = list_new(1);
68 printf("Longueur de la liste: %d\n", list_count(head));
69 list_append(head, 2);
70 list_append(head, 3);
71 list_append(head, 4);
72 printf("Longueur de la liste: %d\n", list_count(head));
73 printf("Valeur a index %d: %d\n", 2, list_get(head, 2));
74 printf("Valeur a index %d: %d\n", 3, list_get(head, 3));
75 printf("Valeur a index %d: %d\n", 4, list_get(head, 4));
76 list_clear(head);
77
78 return 0;
79 }