Exercice TP-Liste Chainées

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

#include <stdio.

h>
#include <stdlib.h>

typedef struct node {


int data;
struct node *Next;
} Node;

void IsEmpty(Node *head) {


if (head == NULL) {
printf("La liste est vide!!");
} else {
printf("La liste n’est pas vide!!");
}
}

Node* creation(Node* head, int Elm[], int n) {


Node* p;
Node* q;
int i;
if (n == 0) {
head = NULL;
} else {
head = (Node*)malloc(sizeof(Node));
p = head;
p->data = Elm[0];
p->Next = NULL;
for (i = 1; i < n; i++) {
q = (Node*)malloc(sizeof(Node));
q->data = Elm[i];
q->Next = NULL;
p->Next = q;
p = q;
}
}
return head;
}

Node *AddinTheBegin(Node *head, int v) {


Node *p;
p = (Node*)malloc(sizeof(Node));
p->data = v;
p->Next = head;
head = p;
return head;
}

Node *AddinTheEnd(Node *head, int v) {


Node *p, *q;
if (head == NULL) {
head = (Node*)malloc(sizeof(Node));
head->data = v;
head->Next = NULL;
} else {
q = head;
while (q->Next != NULL) {
q = q->Next;
}
p = (Node*)malloc(sizeof(Node));
p->data = v;
p->Next = NULL;
q->Next = p;
}
return head;
}

Node* AddinTheMiddle(Node* head, int n, int v) {


Node* p;
Node* q;
p = (Node*)malloc(sizeof(Node));
p->data = n;
p->Next = NULL;
q = head;
while (q != NULL && q->data != v) {
q = q->Next;
}
if (q != NULL) {
p->Next = q->Next;
q->Next = p;
}
return head;
}

void Travers(Node *head) {


Node *p;
p = head;
if (head == NULL) {
printf("La liste est vide");
} else {
while (p != NULL) {
printf("%d ", p->data);
p = p->Next;
}
}
}

int Count(Node *head) {


int i = 0;
Node *p;
p = head;
while (p != NULL) {
i = i + 1;
p = p->Next;
}
return i;
}

Node* supprimerParValeur(Node* head, int v) {


Node* p = head;
Node* q = NULL;
while (p != NULL && p->data != v) {
q = p;
p = p->Next;
}
if (p != NULL) {
if (q != NULL) {
q->Next = p->Next;
} else {
head = p->Next;
}
free(p);
}

return head;
}

void supprimerTousLesNodes(Node** head) {


Node* p = *head;
Node* q;

while (p != NULL) {
q = p->Next;
free(p);
p = q;
}
*head = NULL;
}

int main() {
Node* maListe = NULL;
int elements[] = {10, 20, 30, 40, 50};
int taille = sizeof(elements) / sizeof(elements[0]);
maListe = creation(maListe, elements, taille);
maListe = AddinTheBegin(maListe, 5);
maListe = AddinTheEnd(maListe, 60);
maListe = AddinTheMiddle(maListe, 25, 20);
Travers(maListe);
int nombreDeNoeuds = Count(maListe);
printf("\nNombre de noeuds dans la liste : %d\n", nombreDeNoeuds);

supprimerTousLesNodes(&maListe);

return 0;
}

You might also like