Skip to content

Instantly share code, notes, and snippets.

@antonio-abrantes
Created August 17, 2016 19:26
Show Gist options
  • Save antonio-abrantes/c6e0647cd86d501ef525cb50197fcd17 to your computer and use it in GitHub Desktop.
Save antonio-abrantes/c6e0647cd86d501ef525cb50197fcd17 to your computer and use it in GitHub Desktop.
App para estudo de listas simplesmente encadeadas
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct No{
int conteudo;
struct No *prox;
}no;
no *aloca(){
no *novo=(no *) malloc(sizeof(no));
if(!novo){
printf("Sem memoria disponivel!\n");
exit(1);
}else{
printf("Novo elemento: "); scanf("%d", &novo->conteudo);
return novo;
}
}
void inicia(no *LISTA){
LISTA->prox = NULL;
}
void inserirInicio(no *LISTA){
no *novo = aloca(), *velhaCabeca;
velhaCabeca = LISTA->prox;
LISTA->prox = novo;
novo->prox = velhaCabeca;
}
void inserirFim(no *LISTA){
no *novo = aloca();
novo->prox = NULL;
no *temp = LISTA->prox;
while(temp->prox != NULL)
{
temp = temp->prox;
}
temp->prox = novo;
}
no *retiraInicio(no *LISTA){
no *temp = LISTA->prox;
LISTA->prox = temp->prox;
return temp;
}
no *retiraFinal(no *LISTA){
no *ultimo = LISTA->prox;
no *penultimo = LISTA;
while(ultimo->prox != NULL)
{
penultimo = ultimo;
ultimo = ultimo->prox;
}
penultimo->prox = NULL;
return ultimo;
}
void exibir(no *LISTA){
no *temp = LISTA->prox;
if(temp == NULL){
printf("Lista vazia\n");
}else{
while(temp != NULL)
{
printf("%d ", temp->conteudo);
temp = temp->prox;
}
}
}
int opcao(){
int resp;
printf("Digite uma opcao: ");
scanf("%d", &resp);
return resp;
}
int menu(no *LISTA){
no *temp;
system("cls");
printf("1 - Incluir no inicio\n");
printf("2 - Incluir no final\n");
printf("3 - Listar\n");
printf("4 - Retirar do final\n");
printf("5 - Retirar do inicio\n");
printf("6 - Sair\n");
int resp = opcao();
switch(resp)
{
case 1:
inserirInicio(LISTA);
break;
case 2:
inserirFim(LISTA);
break;
case 3:
printf("Lista: ");
exibir(LISTA);
getch();
break;
case 4:
temp = retiraFinal(LISTA);
printf("Retira ultimo: %d\n", temp->conteudo);
getch();
break;
case 5:
temp = retiraInicio(LISTA);
printf("Retira primeiro: %d\n", temp->conteudo);
getch();
break;
case 6:
return 1;
default:
printf("Opcao invalida!\n");
break;
}
return 0;
}
int main(int argc, char** argv)
{
no *LISTA = (no*)malloc(sizeof(no));
inicia(LISTA);
while(1)
{
if(menu(LISTA) == 1)
break;
}
//exibir(LISTA);
/*/inserirInicio(LISTA);
inserirInicio(LISTA);
inserirInicio(LISTA);
exibir(LISTA);printf("\n");
printf("INSEIR NO FIM\n");
inserirFim(LISTA);
inserirFim(LISTA);
exibir(LISTA); printf("\n");
no *ret = retiraInicio(LISTA);
printf("Retirado do inicio: %d\n", ret->conteudo);
ret = retiraFinal(LISTA);
printf("Retirado do final: %d\n", ret->conteudo);
exibir(LISTA);*/
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment