Advertisement
lucast0rres

Lista encadeada ordenada

May 21st, 2018
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct tLista
  5. {
  6.     int valor;
  7.     struct tLista *prox;
  8.  
  9. } lista;
  10.  
  11. void inserir(lista **p)
  12. {
  13.     lista *atual, *novo, *anterior;
  14.     int num;
  15.  
  16.     novo = (lista *) malloc(sizeof(lista));
  17.  
  18.     atual = *p;
  19.     anterior = NULL;
  20.  
  21.     printf("Insira um valor: ");
  22.     scanf("%d", &num);
  23.  
  24.     novo->valor = num;
  25.  
  26.     if(atual == NULL){
  27.         novo->prox = NULL;
  28.         *p = novo;
  29.     } else{
  30.         while(atual != NULL && atual->valor < num){
  31.             anterior = atual;
  32.             atual = atual->prox;
  33.         }
  34.  
  35.         novo->prox = atual;
  36.  
  37.         if(anterior == NULL){
  38.             *p = novo;
  39.         } else{
  40.             anterior->prox = novo;
  41.         }
  42.     }
  43. }
  44.  
  45. void mostraLista(lista *p)
  46. {
  47.     while(p != NULL)
  48.     {
  49.         printf("Valor: %d\n", p->valor);
  50.         p = p->prox;
  51.     }
  52. }
  53.  
  54. int main(void)
  55. {
  56.  
  57.     lista *inicio = NULL;
  58.     char opcao = 's';
  59.  
  60.     while( opcao == 's' || opcao == 'S' )
  61.     {
  62.         inserir(&inicio);
  63.  
  64.         printf("Deseja inserir outro? (S/N)\n");
  65.         scanf(" %c", &opcao);
  66.     }
  67.  
  68.     mostraLista(inicio);
  69.  
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement