Prévia do material em texto
#include <stdio.h> #include <malloc.h> #define true 1 #define false 0 typedef int bool; typedef int KEY; typedef struct { KEY chave; } REGISTRO; typedef struct aux { REGISTRO reg; struct aux* prox; } ELEMENTO, *PONT; typedef struct { PONT inicio; } LISTA; void initialize(LISTA *lista){ lista->inicio = NULL; } int count(LISTA *lista){ PONT fim = lista->inicio; int tam = 0; while(fim!=NULL){ tam++; fim = fim->prox; } return tam; } void print(LISTA *lista){ PONT fim = lista->inicio; printf("Lista: "); while(fim!=NULL) { printf("%i ", fim->reg.chave); fim = fim->prox; } printf("\n"); } PONT busca(LISTA *lista, KEY ch){ PONT ponto = lista->inicio; while(ponto!=NULL){ if(ponto->reg.chave == ch) return ponto; ponto = ponto->prox; } return NULL; } PONT buscaAtualAnt(LISTA *lista, KEY ch, PONT *ant) { *ant = NULL; PONT atual = lista->inicio; while((atual != NULL) && (atual->reg.chave < ch)) { *ant = atual; atual = atual->prox; } if((atual != NULL) && (atual->reg.chave == ch)) return atual; return NULL; } bool inserirEmOrdem(LISTA *lista, REGISTRO reg){ KEY ch = reg.chave; PONT ant, i; i = buscaAtualAnt(lista,ch,&ant); if(i!=NULL) return false; i = (PONT) malloc(sizeof(ELEMENTO)); i->reg = reg; if(ant == NULL) { i->prox = lista->inicio; lista->inicio = i; } else { i->prox = ant->prox; ant->prox = i; } return true; } bool excluiElemento(LISTA *lista, KEY ch){ PONT ant, i; i = buscaAtualAnt(lista,ch,&ant); if(i==NULL) return false; if(ant==NULL) lista->inicio = i->prox; else ant->prox = i->prox; free(i); return true; } void reinicializar(LISTA *lista){ PONT fim = lista->inicio; while (fim != NULL){ PONT apagar = fim; fim = fim->prox; free(apagar); } lista->inicio = NULL; } void main(){ LISTA lista; initialize(&lista); REGISTRO r1,r2,r3,r4; r1.chave = 1; r2.chave = 2; r3.chave = 3; r4.chave = 4; inserirEmOrdem(&lista, r2); inserirEmOrdem(&lista, r4); inserirEmOrdem(&lista, r1); inserirEmOrdem(&lista, r3); print(&lista); excluiElemento(&lista, 3); print(&lista); reinicializar(&lista); print(&lista); }