Advertisement
madegoff

queue

Jun 15th, 2023 (edited)
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.02 KB | None | 0 0
  1. #include "header.h"
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4.  
  5. int queue_add(void* new_object, queue_object* queue){
  6.  
  7.     queue_object *new_el = malloc(sizeof(queue_object));
  8.  
  9.     if (new_object == NULL){
  10.         return 1;
  11.     }
  12.     else
  13.     {
  14.         new_el->object = new_object;
  15.  
  16.         if(queue->next == NULL){
  17.             queue->next = new_el;
  18.             new_el->next = NULL;
  19.         }
  20.         else{
  21.  
  22.             queue_object *current_el = queue->next;
  23.             queue_object *next_el;
  24.  
  25.             while(current_el->next != NULL){
  26.  
  27.                 next_el = current_el->next;
  28.                 current_el = next_el;
  29.  
  30.             }
  31.  
  32.             current_el->next = new_el;
  33.             new_el->next = NULL;
  34.         }
  35.  
  36.      return 0;
  37.     }
  38. }
  39.  
  40. void* queue_poll(queue_object* queue){
  41.  
  42.     if(queue == NULL || queue->next == NULL){//wenn queue leer
  43.  
  44.         return NULL;
  45.     }
  46.     else{
  47.  
  48.         queue_object *prev_el = queue->next; //das zu loeschende element
  49.         queue_object *next_el = prev_el->next; //das naechste element
  50.  
  51.         queue->next = next_el;
  52.  
  53.         void* obj = prev_el->object;
  54.         free(prev_el); //letztes element loeschen
  55.  
  56.         return obj;
  57.     }
  58. }
  59.  
  60. queue_object* new_queue(){
  61.  
  62.     queue_object *head = malloc(sizeof(queue_object));
  63.     head->next = NULL;
  64.     head->object = NULL;
  65.  
  66.     return head;
  67. }
  68.  
  69.  
  70. void free_queue(queue_object* queue){
  71.  
  72.     if (queue == NULL){
  73.         return;
  74.     }
  75.     else{
  76.  
  77.         queue_object *current_el = queue->next;
  78.         queue_object *next_el;
  79.  
  80.         while(current_el != NULL){ //&current_el->next != NULL?
  81.             next_el = current_el->next;
  82.             free(current_el);
  83.             current_el = next_el;
  84.         }
  85.     }
  86.     free(queue);
  87.  
  88. }
  89.  
  90. void* queue_peek(queue_object* queue){
  91.  
  92.     if(queue == NULL || queue->next == NULL){//wenn queue leer
  93.  
  94.         return NULL;
  95.     }
  96.     else{
  97.         queue_object *prev_el = queue->next;
  98.         void* obj = prev_el->object;
  99.         return obj;
  100.     }
  101. }
  102.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement