Untitled
unknown
c_cpp
3 years ago
3.1 kB
4
Indexable
#include <stdio.h> #include <stdlib.h> #include "llist.h" #include "list.h" #define N 100 #ifdef LLIST_SOL static struct node *node_alloc(int elem) { struct node *tmp = (struct node *)malloc(sizeof(struct node)); if (tmp != NULL) { tmp->elem = elem; tmp->next = NULL; } return tmp; } static int node_delete(struct node *L) { if (L == NULL || L->next == NULL) { return 1; } else { struct node *tmp = L->next; L->next = tmp->next; free(tmp); return 0; } } static int node_insert(struct node *L, int elem) { if (L == NULL) { return 1; } else { struct node *tmp = node_alloc(elem); if (tmp != NULL) { tmp->next = L->next; L->next = tmp; } return tmp == NULL; } } static struct node *node_search(struct node *L, unsigned int i) { while (i-- > 0 && L != NULL) L = L->next; return L; } /*inverte l'ordine della lista*/ void list_invert(list *L) { int n = list_length(*L); int i, scambio; struct node *tmp1, *tmp2; for (i = 0; i < n / 2; i++) { tmp1 = node_search(*L, i); tmp2 = node_search(*L, n-1-i); scambio = tmp1->elem; tmp1->elem = tmp2->elem; tmp2->elem = scambio; } } /*inverte l'ordine della lista*/ void list_invert2(list *L) { struct node *tmp, *tmp1, *tmp2; if (L != NULL && *L != NULL && (*L)->next != NULL) { tmp1 = *L; tmp2 = tmp1->next; tmp1->next = NULL; while (tmp2 != NULL) { tmp= tmp2->next; tmp2->next = tmp1; tmp1 = tmp2; tmp2 = tmp; } *L = tmp1; } } /*ritorna l'elemento che si trova nel posto mediano della lista*/ int middle_select(list L) { return indx_select(&L, list_length(L) / 2); } int middle_select2(list L) { struct node *tmp = L; struct node *tmp2 = L; while (tmp2 != NULL && tmp2->next != NULL) { tmp = tmp->next; tmp2 = tmp2->next->next; } return tmp->elem; } /*ritorna la lunghezza della lista*/ int list_length(list L) { int len=0; while (L != NULL) { len++; L = L->next; } return len; } //elimina gli elementi in posizione dispari int odd_delete(list *L) { int i=0; struct node*tmp = *L; while (tmp != NULL) { node_delete(tmp); i++; tmp = tmp->next; } return i; } //elimina gli elementi in posizione pari int even_delete(list *L) { int i = 1; struct node*tmp = *L; *L = (*L)->next; free(tmp); i+=odd_delete(L); return i; } /*stampa elementi e relativa posizione */ void list_ordprint(list L) { int i = 0; while (L != NULL) { printf("(%d,%d) ", i++, L->elem); L = L->next; } printf("\n"); } /*salva elementi su file */ void list_save(list L, char *filename) { FILE* outF = fopen(filename, "w"); while (L != NULL) { fprintf(outF, "%d ", L->elem); L = L->next; } printf("\n"); fclose(outF); } /*carica elementi da file */ void list_load(list *L, char *filename) { FILE* inF = fopen(filename, "r"); int i=1; while (fscanf(inF, "%d ", &i)>0) { tail_insert(L, i); } fclose(inF); } #endif
Editor is loading...