Ho scritto due righe di codice durante la pausa caffe... sicuramente puo esser ottimizzato. Genera casualmente una lista di 100 elementi. Il valore di ciascuno è intero e casuale. La seconda lista è formata dagli elementi in posizione multipla di N ed il cui valore è maggiore del precedente.
codice:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct doublelinked{
int num;
struct doublelinked *prev;
struct doublelinked *next;
};
void add(int, struct doublelinked **);
void init(int, struct doublelinked **);
void list_forward(struct doublelinked **);
void init(int nr, struct doublelinked **first){
int i = 0;
struct doublelinked *new;
for(; i < nr; i++){
if(!(new = (struct doublelinked *)malloc(sizeof(struct doublelinked))))
abort();
(*(new)).num = rand()%100;
(*(new)).next = *first;
(*(new)).prev = NULL;
if(*first != NULL)
(*(first))->prev = new;
*first = new;
}
}
void list_forward(struct doublelinked **first){
struct doublelinked *current;
for(current = *first; current != NULL; current = (*(current)).next)
printf("%d ", (*(current)).num);
printf("\n\n");
}
void add(int nr, struct doublelinked **first){
struct doublelinked *new, *current;
if(!(new = (struct doublelinked *)malloc(sizeof(struct doublelinked))))
abort();
(*(new)).num = nr;
if(*first == NULL){
*first = new;
(*(first))->prev = NULL;
(*(first))->next = NULL;
}
if(*first != NULL){
for(current = *first; (*(current)).next != NULL; current = (*(current)).next);
(*(current)).next = new;
(*(new)).next = NULL;
(*(new)).prev = current;
}
}
void main(){
int i, N = 4;
struct doublelinked *first_1 = NULL, *first_2 = NULL, *current;
srand(time(NULL));
init(100, &first_1);
list_forward(&first_1);
for(i = 0, current = first_1; current != NULL; current = (*(current)).next, i++){
if(i == 0){
add((*(current)).num, &first_2);
}
if(((i+1)%N == 0) && (*(current)).num > (*(current)).prev->num)
add((*(current)).num, &first_2);
}
list_forward(&first_2);
}