Liste
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int value;
struct node *next;
} *IntList;
IntList emptyIntList = NULL;
//tipareste o lista
void printIntList(IntList a) {
printf("<");
if(a != emptyIntList) {
IntList c = a;
while(c!=emptyIntList) {
printf("%d",c->value);
if(c->next!=emptyIntList) printf(",");
c = c->next;
}
}
printf(">\n");
}
//construieste o lista cu head x si tail a
IntList cons(int x, IntList a) {
IntList tmp = malloc(sizeof(struct node));
tmp->value = x;
tmp->next = a;
return tmp;
}
//intoarce o lista care nu mai contine primul element din a
IntList tail(IntList a) {
if(a == emptyIntList) {
printf("You try to apply tail on the empty list!\n");
exit(1);
}
return a->next;
}
//returneaza valoarea primului element din lista
int head(IntList a) {
if(a == emptyIntList) {
printf("You try to apply head on the empty list!\n");
exit(1);
}
return a->value;
}
//construieste o lista pana la a
//elementele adaugate sunt in ordine descrescatoare
IntList reverseSequence(int a) {
if(a == 0) {
return cons(a,emptyIntList);
} else {
return cons(a,reverseSequence(a-1));
}
}
//lungimea unei liste
int length (IntList a)
{
if(a==emptyIntList)
return 0;
else return 1+length(tail(a));
}
//numarul de elemente pare dintr-o lista
int par (IntList a)
{
if(a==emptyIntList)
return 0;
else if((head(a))%2==0)
return 1+par(tail(a));
else
return par(tail(a));
//creearea unei liste cu numere pare
}
IntList listpar(IntList a)
{
if(a==emptyIntList)
return emptyIntList;
else if(head(a)%2==0)
return cons(head(a), listpar(tail(a)));
else
return listpar(tail(a));
}
int main() {
//se construieste lista 1,2,3,4
IntList a = cons(1,cons(2,cons(3,cons(4,emptyIntList))));
//se tipareste lista
printIntList(a);
//se construieste lista 10,9,8,7,6,5,4,3,2,1
//se tipareste lista
printIntList(reverseSequence(10));
printf("%u\n", length(a));
printf("%u\n" , par(a));
printIntList(listpar(a));
return 0;
}