En C 


NB : les fonctions dont le code est donné ci-dessous correspondent à celles qui ont été vues en TD en Java. Pour les autres, elles sont à compléter (cf. TP n°2)

La déclaration des structures/fonctions : listsimple.h

typedef struct cell {
  int value;
  struct cell* next;
} Cell;
 
typedef struct list {
  Cell* head;
  int size;
} List;
 
List* listCreate();
Cell* listFind(List* l, int value);
Cell* listGet(List* l, int index);
Cell* listAppend(List* l, int value);
Cell* listInsert(List* l, int value, int index);
Cell* listReplace(List* l, int value, int index);
Cell* listRemoveAt(List* l, int index);
Cell* listRemove(List* l, int value);
void listPrint(List* l);
 

 

la définition des fonctions : listsimple.c

#include <stdio.h>
#include <stdlib.h>
#include "listsimple.h"
 
List* listCreate() {
  List* l = (List*)malloc(sizeof(List));
  if (l != NULL) {
    l->head = NULL;
    l->size = 0;
  }
  return l;
}
 
Cell* listFind(List* l, int value) {
 
  Cell* cell = l->head;
  while ((cell != NULL) && (cell->value != value)) {
    cell = cell->next;
  }
  return cell;
}
 
Cell* listGet(List* l, int index) {
 
  Cell* cell = l->head;
 
  // A COMPLETER
 
  return cell;
}
 
Cell* listAppend(List* l, int value) {
  Cell* cell = NULL;
  Cell* new = NULL;
  new = (Cell*)malloc(sizeof(Cell));
  new->next = NULL;
  new->value = value;
  if (l->size == 0) {
    l->head = new;
  }
  else {
    cell = listGet(l,l->size-1);
    cell->next = new;
  }
  l->size += 1;
  return new;
}
 
Cell* listInsert(List* l, int value, int index) {
  Cell* cell = NULL;
  Cell* new = NULL;
 
  // A COMPLETER
 
  return new;
}
 
Cell* listReplace(List* l, int value, int index) {
 
  Cell* cell = NULL;
 
  // A COMPLETER
 
  return cell; 
}
 
Cell* listRemoveAt(List* l, int index) {
 
  Cell* cell = NULL;
  Cell* tmp = NULL;
  if (index >= l->size) {
    return;
  }
  else if (index == 0) {
    tmp = l->head;
    l->head = l->head->next;
  }
  else {
    cell = listGet(l,index-1);
    tmp = cell->next;
    cell->next = tmp->next;
  }
  l->size -= 1;
  return tmp;
}
 
Cell* listRemove(List* l, int value) {
 
  Cell* cell = l->head;
 
  // A COMPLETER
 
  return cell;
}
 
void listPrint(List* l) {
 
  Cell* cell = l->head;
  while (cell != NULL) {
    printf("%d -> ",cell->value);
    cell = cell->next;
  }
  printf("\n");
}
 

 

 Un programme de test : testlist.c

#include <stdio.h>
#include "listsimple.h"
 
int main(int argc, char** argv) {
 
  List* l;
 
  l = listCreate();
  listAppend(l,3);
  listAppend(l,5);
  listAppend(l,1);
  listInsert(l,15,1);
  listInsert(l,5,10); // indice > size
  listPrint(l);
  listRemoveAt(l,2);
  listRemove(l,3); // suppr head
  listRemove(l,5); // suppr queue
  listRemove(l,33); // suppr none
  listPrint(l);
  return 0;
}
 
  • Création de l'exécutable (compilation + édition de liens) : gcc listsimple.c testsimple.c -o testimple