Advertisement
Guest User

cola.c

a guest
Apr 22nd, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | None | 0 0
  1. #include <stdbool.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4.  
  5. typedef struct nodo {
  6.     void* dato;
  7.     struct nodo* prox;
  8. } nodo_t;
  9.  
  10. typedef struct cola {
  11.     nodo_t* primero;
  12.     nodo_t* ultimo;
  13. } cola_t;
  14.  
  15. nodo_t* nodo_crear(void* valor){
  16.     nodo_t* nodo = malloc(sizeof(nodo_t));
  17.     if (!nodo) return NULL;
  18.     nodo->dato = valor;
  19.     nodo->prox = NULL;
  20.     return nodo;
  21. }
  22.  
  23. cola_t* cola_crear(){
  24.     cola_t* cola = malloc(sizeof(cola_t));
  25.     if(!cola)   return NULL;
  26.     cola->primero = NULL;
  27.     cola->ultimo = NULL;
  28.     return cola;
  29. }
  30. bool cola_esta_vacia(const cola_t *cola){
  31.     return !cola->primero;
  32. }
  33.  
  34. void* cola_desencolar(cola_t *cola){
  35.     if(cola_esta_vacia(cola))   return NULL;
  36.     void* valor = cola->primero->dato;
  37.     nodo_t* nodo_aux = cola->primero;
  38.     cola->primero = cola->primero->prox;
  39.     free(nodo_aux);
  40.     return valor;
  41. }
  42.  
  43. void cola_destruir(cola_t *cola, void destruir_dato(void*)){
  44.     void* dato_aux;
  45.     while(!cola_esta_vacia(cola)){
  46.         dato_aux = cola_desencolar(cola);
  47.         if(destruir_dato)   destruir_dato(dato_aux);
  48.     }
  49.     free(cola);
  50. }
  51.  
  52. bool cola_encolar(cola_t *cola, void* valor){
  53.     nodo_t* nodo = nodo_crear(valor);
  54.     if(!nodo)   return false;
  55.     if(cola_esta_vacia(cola)) cola->primero = nodo;
  56.     else cola->ultimo->prox = nodo;
  57.     cola->ultimo = nodo;
  58.     return true;
  59. }
  60. void* cola_ver_primero(const cola_t *cola){
  61.     if(cola_esta_vacia(cola))   return NULL;
  62.     return cola->primero->dato;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement