PedroHMM

LISTASEQUENCIAL

Apr 4th, 2012
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<conio.h>
  3. #include<stdlib.h>
  4.  
  5. #define MAX 5
  6.  
  7. typedef struct
  8. {
  9.         int chave;
  10.         int valor;
  11.  
  12. }REGISTRO;
  13.  
  14. typedef struct
  15. {
  16.         REGISTRO A[MAX];
  17.         int nElementos;
  18.  
  19. }LISTA;
  20.  
  21. void inicializar(LISTA *l)
  22. {
  23.      l->nElementos = 0;
  24. }
  25.  
  26. REGISTRO set_Registro(int ch, int vl)
  27. {
  28.          REGISTRO reg;
  29.          reg.chave = ch;
  30.          reg.valor = vl;
  31.          return reg;
  32. }
  33.  
  34. int size (LISTA *l)
  35. {
  36.     return(l->nElementos);
  37. }
  38.  
  39. void imprimir (LISTA *l)
  40. {
  41.      int i;
  42.      for(i= 0 ; i<size(l); i++)
  43.             printf("\n %i -+- %i", l->A[i].chave , l->A[i].valor);
  44. }
  45.  
  46. int buscar(LISTA *l, int chave)
  47. {
  48.     int i;
  49.     for(i=0; i<l->nElementos; i++)
  50.     {
  51.              if(chave == l->A[i].chave) return (i);          
  52.     }
  53.              return (-1);
  54.  
  55. }
  56.  
  57. bool anexar(LISTA *l, REGISTRO r)
  58. {
  59.  
  60.      if(buscar(l,r.chave)!=(-1)) return false;
  61.         if(l->nElementos == MAX) return false;
  62.             l->A[l->nElementos]= r;
  63.             l->nElementos++;
  64.             return true;
  65.  
  66. }
  67.  
  68. bool inserir(LISTA *l, int i, REGISTRO r)
  69. {
  70.     int j;
  71.     if((l->nElementos >= MAX) || (i<0) || (i > (l->nElementos)))
  72.         return false;
  73.         for(j = l->nElementos -1; j >= i; j--)
  74.         {
  75.             l->A[j +1] = l->A[j];
  76.         }
  77.         l->A[i] = r;
  78.         l->nElementos++;
  79.         return  true;
  80. }
  81.  
  82. bool excluir(LISTA *l, int ch)
  83. {
  84.      int pos = buscar(l, ch);
  85.      if(pos == -1) return false; // chave já existente
  86.      int i;
  87.      for(i = pos ; i <(l->nElementos -1); i++ )
  88.      {
  89.            l->A[i] = l->A[i+1];
  90.      }
  91.            l->nElementos = l->nElementos -1;
  92.            return true;
  93.      
  94. }
  95.  
  96. main()
  97. {
  98.       LISTA Lista;
  99.       inicializar(&Lista);
  100.       anexar(&Lista,set_Registro(1,10));
  101.       anexar(&Lista,set_Registro(2,20));
  102.       anexar(&Lista,set_Registro(3,30));
  103.       imprimir(&Lista);
  104.       getch();
  105.       inserir(&Lista,3, set_Registro(4,40));
  106.       imprimir(&Lista);
  107.       getch();
  108.       excluir(&Lista, 4);
  109.       imprimir(&Lista);
  110.       getch();
  111. }
Advertisement
Add Comment
Please, Sign In to add comment