Advertisement
Guest User

Untitled

a guest
May 5th, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.99 KB | None | 0 0
  1. #include<stdlib.h>
  2. #include<stdio.h>
  3.  
  4. void init(void);
  5. void add(int);
  6. int pop(void);
  7. void cleanup(void);
  8. void error(void);
  9.  
  10. struct queue{
  11.   int a;
  12.   struct queue * next;
  13. };
  14.  
  15. struct queue * last = 0;
  16. struct queue * now = 0;
  17. int count = 0;
  18.  
  19. void init(){
  20.   if((now = malloc(sizeof(struct queue))) == NULL) error();
  21.   last = now;
  22. }
  23.  
  24. void add(int x){
  25.   if(now == 0) error();
  26.   if((now->next = malloc(sizeof(struct queue))) == NULL) error();
  27.   now->a = x;
  28.   now = now->next;
  29.   count++;
  30. }
  31.  
  32. int pop(){
  33.   if((now == 0) || (count == 0)) error();
  34.   int temp;
  35.   extern int count;
  36.  
  37.   struct queue * past = last;
  38.   temp = last->a;
  39.   last = last->next;
  40.   count--;
  41.   free(past);
  42.   return temp;
  43. }
  44.  
  45. void cleanup(){
  46.   if(count == 0){
  47.   last = 0;
  48.   now = 0;
  49. }
  50.   else{
  51.     struct queue * past = last;
  52.     while(count != 1){
  53.       last = last->next;
  54.       free(past);
  55.     }
  56.     free(last);
  57.   }
  58. }
  59.  
  60. void error(){
  61.   fputs("ERROR", stderr);
  62.   cleanup();
  63.   exit(EXIT_FAILURE);
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement