Advertisement
Guest User

Untitled

a guest
Mar 21st, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.61 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef int bool;
  5.  
  6. #define rep(a,b) for(int a=0;a<b;a++)
  7. #define true 1
  8. #define false 0
  9.  
  10. struct queue {
  11.     int front;
  12.     int back;
  13.     int size;
  14.     int *arr;
  15.     int maxSize;
  16. };
  17.  
  18. struct queue * createQueue(int size){
  19.     struct queue * r = (struct queue *) malloc(sizeof(struct queue));
  20.     r-> arr = (int *) malloc(sizeof(int) * size);
  21.     r->front = 0;
  22.     r->back = 0;
  23.     r->size = 0;
  24.     r->maxSize = size;
  25.  
  26.     return r;
  27. }
  28.  
  29. void deleteQueue(struct queue *q){
  30.     free(q->arr);
  31.     free(q);
  32. }
  33.  
  34. bool isEmpty(struct queue *q){
  35.     return q->size == 0;
  36. }
  37.  
  38. bool isFull(struct queue *q){
  39.     return q->size == q->maxSize;
  40. }
  41.  
  42. int size(struct queue *q){
  43.     return q->size;
  44. }
  45.  
  46. bool enqueue(struct queue * q, int value){
  47.     if(isFull(q)){
  48.         printf("Cannot enqueue value '%d'to the queue. Queue full.\n", value);
  49.         return false;
  50.     }
  51.  
  52.     q->back ++;
  53.     q->back %= q->maxSize;
  54.     q->size ++;
  55.  
  56.     q->arr[ q-> back ] = value;
  57.     if(q->size == 1) q->front = q->back;
  58.    
  59.     return true;
  60. }
  61.  
  62. int dequeue(struct queue *q){
  63.     if(isEmpty(q)){
  64.         printf("Cannot dequeue. Queue is empty.\n");
  65.         return -1;
  66.     }
  67.  
  68.     int value = q->arr[ q->front ];
  69.  
  70.     q->front ++;
  71.     q->front %= q->maxSize;
  72.     q->size --;
  73.  
  74.     return value;
  75. }
  76.  
  77.  
  78. int main(){
  79.     int n,m;
  80.     printf("Input n m: ");
  81.     scanf("%d%d", &n, &m);
  82.  
  83.     struct queue *q = createQueue(n);
  84.     rep(i,n) enqueue(q, i);
  85.     int counter = 0;
  86.     while(size(q) > 1){
  87.         counter++;
  88.         int current = dequeue(q);
  89.         if(counter != m) enqueue(q, current);
  90.         else printf("Eliminating position %d\n", current);
  91.         counter %= m;
  92.     }
  93.  
  94.     printf("Left out position: %d\n", dequeue(q));
  95.     return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement