Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- struct bloco
- {
- int num;
- struct bloco *prox;
- };
- struct bloco *aux, *aux2, *fim, *inicio;
- void iniciar_lista(void);
- void inserir(void);
- void retirar(void);
- void pesquisar(int);
- void listar(void);
- void desalocar_lista(void);
- int main()
- {
- int opcao = -1;
- iniciar_lista();
- while(opcao != 4)
- {
- printf("\nO que quer fazer?\n");
- printf("\n1. Inserir elemento na lista.\n");
- printf("\n2. Retirar elemento da lista.\n");
- printf("\n3. Ver a lista.\n");
- printf("\n4. Sair\n");
- printf("\nOpção desejada: ");
- scanf("%d", &opcao);
- switch(opcao)
- {
- case 1: inserir(); break;
- case 2: retirar(); break;
- case 3: listar(); break;
- case 4: desalocar_lista(); return 0; break;
- default: printf("\nOpção inválida.\n");
- }
- }
- }
- void iniciar_lista(void)
- {
- inicio = (struct bloco *)malloc(sizeof(struct bloco));
- inicio->num = -1;
- inicio->prox = NULL;
- }
- void inserir(void)
- {
- int numero;
- aux = (struct bloco *)malloc(sizeof(struct bloco));
- printf("\nQue número quer inserir?\n");
- scanf("%d", &numero);
- aux->num = numero;
- aux->prox = NULL;
- if(inicio->prox == NULL)
- {
- inicio->prox = aux;
- fim = aux;
- }
- else
- {
- fim->prox = aux;
- fim = aux;
- }
- }
- void retirar(void)
- {
- int numero;
- if(inicio->prox != NULL)
- {
- printf("\nQue número quer retirar?\n");
- scanf("%d", &numero);
- pesquisar(numero);
- if(aux == NULL)
- printf("\nNúmero não encontrado.\n");
- else
- {
- aux2->prox = aux->prox;
- if(aux == fim) fim = aux2;
- free(aux);
- }
- }
- else
- printf("\nLista vazia.\n");
- }
- void pesquisar(int x)
- {
- aux2 = inicio;
- aux = inicio->prox;
- while(aux->num != x)
- {
- if(aux == fim) break;
- aux = aux->prox;
- aux2 = aux2->prox;
- }
- if(aux->num != x)
- aux = NULL;
- }
- void listar(void)
- {
- aux = inicio->prox;
- if(aux != NULL)
- {
- while(aux != NULL)
- {
- printf("%d -> ", aux->num);
- aux = aux->prox;
- }
- printf("NULL\n\n");
- }
- else
- printf("\nLista vazia.\n\n");
- }
- void desalocar_lista(void)
- {
- aux2 = inicio;
- aux = inicio->prox;
- while(aux2 != NULL)
- {
- free(aux2);
- aux2 = aux;
- if(aux != NULL) aux = aux->prox;
- }
- }
Add Comment
Please, Sign In to add comment