Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- #include <malloc.h>
- typedef struct estrutura
- {
- int chave;
- estrutura *prox;
- } NO;
- typedef struct
- {
- NO* inicio;
- } LISTA;
- void inicializar(LISTA *l)
- {
- l->inicio = NULL;
- }
- void exibir(LISTA *l)
- {
- NO* p = l->inicio;
- while(p)
- {
- printf("%i\t", p->chave);
- p = p->prox;
- }
- printf("\n");
- }
- NO* buscar(LISTA *l, int chave, NO* *ant)
- {
- NO* p = l->inicio;
- *ant = NULL;
- while(p)
- {
- if(p->chave == chave) return p;
- *ant = p;
- p = p->prox;
- }
- return NULL;
- }
- bool anexar(LISTA *l, int chave)
- {
- NO* ant;
- NO* novo = buscar(l, chave, &ant);
- if(novo) return false;
- novo = (NO*) malloc(sizeof(NO));
- novo->chave = chave;
- if(!l->inicio)
- {
- l->inicio = novo;
- novo->prox = NULL;
- }
- else
- {
- if(!ant)
- {
- novo->prox = l->inicio;
- l->inicio = novo;
- }
- else
- {
- novo->prox = ant->prox;
- ant->prox = novo;
- }
- }
- return true;
- }
- int size(LISTA *l)
- {
- NO* p = l->inicio;
- int cont = 0;
- while(p)
- {
- cont++;
- p = p->prox;
- }
- return cont;
- }
- bool inserir(LISTA *l, int chave, int pos)
- {
- if(pos <0) return false;
- NO* ant;
- NO* novo = buscar(l, chave, &ant);
- if(novo) return false;
- novo = (NO*) malloc(sizeof(NO));
- novo->chave =chave;
- if(pos == 0)
- {
- novo->prox = l->inicio;
- l->inicio = novo;
- }
- if(pos >= size(l))
- {
- ant->prox = novo;
- novo->prox = NULL;
- }
- else
- {
- int cont=0;
- NO* p = l->inicio;
- while(p)
- {
- if(cont == pos -1)
- {
- novo->prox = p->prox;
- p->prox =novo;
- return true;
- }
- else
- {
- cont ++;
- p =p->prox;
- }
- }
- }
- return true;
- }
- bool excluir(LISTA *l, int chave)
- {
- NO* ant;
- NO* p = buscar(l, chave, &ant);
- if(!p) return false;
- if(!ant) l->inicio = p->prox;
- else ant->prox = p->prox;
- free(p);
- return true;
- }
- void destruir(LISTA *l)
- {
- NO* p =l->inicio;
- NO* aux;
- while(p)
- {
- aux = p->prox;
- free(p);
- p = aux;
- }
- l->inicio = NULL;
- }
- main()
- {
- LISTA l;
- inicializar(&l);
- anexar(&l, 0);
- anexar(&l, 1);
- anexar(&l, 2);
- anexar(&l, 3);
- anexar(&l, 4);
- exibir(&l);
- getch();
- inserir(&l, 80, 3);
- exibir(&l);
- getch();
- inserir(&l, 50, 0);
- exibir(&l);
- getch();
- inserir(&l, 100, 100000000);
- exibir(&l);
- getch();
- inserir(&l, 2000, 55555);
- exibir(&l);
- getch();
- }
Advertisement
Add Comment
Please, Sign In to add comment