Advertisement
renix1

Lista encadeada simples

Mar 30th, 2019
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct lista {
  5.     int n;
  6.     struct lista *prox;
  7. };
  8.  
  9. void inserirInicio(struct lista **celula, int numero) {
  10.     struct lista *novoElemento;
  11.     novoElemento = malloc(sizeof(struct lista));
  12.     novoElemento->n = numero;
  13.     if (*celula == NULL) {
  14.         *celula = novoElemento;
  15.         novoElemento->prox = NULL;
  16.     } else {
  17.         novoElemento->prox = *celula;
  18.         *celula = novoElemento;
  19.     }
  20. }
  21.  
  22. void inserirFinal(struct lista **celula, int numero) {
  23.     struct lista *novoElemento;
  24.     novoElemento = malloc(sizeof(struct lista));
  25.     novoElemento->n = numero;
  26.     struct lista *elementoAtual;
  27.     elementoAtual = *celula;
  28.     while (elementoAtual->prox != NULL) {
  29.         elementoAtual = elementoAtual->prox;
  30.     }
  31.     elementoAtual->prox = novoElemento;
  32.     novoElemento->prox = NULL;
  33. }
  34.  
  35. void printar(struct lista **celula) {
  36.     struct lista *elementoAtual;
  37.     elementoAtual = *celula;
  38.     while (elementoAtual != NULL)
  39.     {
  40.         printf("%d ", elementoAtual->n);
  41.         elementoAtual = elementoAtual->prox;
  42.     }
  43.     printf("\n");
  44. }
  45.  
  46. int main (void) {
  47.     struct lista *head = NULL;
  48.     inserirInicio(&head, 5);
  49.     inserirInicio(&head, 10);
  50.     inserirInicio(&head, 25);
  51.     inserirInicio(&head, 30);
  52.     inserirFinal(&head, 3);
  53.     printar(&head);
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement