Adding TP 8 exo3
[TD_C.git] / TP_8 / exo3 / exo3.c
CommitLineData
7c4bfcc0
JB
1#include <stdio.h>
2#include <stdlib.h>
3
4/** Display a prompt to the user then wait for an integer input. */
5int 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 */
13typedef struct link_s {
14 int value;
15 struct link_s* next;
16} link_t;
17
18link_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
26void 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
34unsigned 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
45int list_get(link_t* head, unsigned index) {
46
47 if (index < list_count(head)) {
48 for (int i = 0; i < index; i++) {
49 head = head->next;
50 }
51 return head->value;
52 } else {
53 return -1;
54 }
55}
56
57void list_clear(link_t* link) {
58 free(link);
59}
60
61int main() {
62 link_t* head = list_new(1);
63 printf("Longueur de la liste: %d\n", list_count(head));
64 list_append(head, 2);
65 list_append(head, 3);
66 list_append(head, 4);
67 printf("Longueur de la liste: %d\n", list_count(head));
68 printf("Valeur a index %d: %d\n", 2, list_get(head, 2));
69 printf("Valeur a index %d: %d\n", 3, list_get(head, 3));
70 printf("Valeur a index %d: %d\n", 4, list_get(head, 4));
71 list_clear(head);
72
73 return 0;
74}