Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef int bool;
- #define rep(a,b) for(int a=0;a<b;a++)
- #define true 1
- #define false 0
- struct queue {
- int front;
- int back;
- int size;
- int *arr;
- int maxSize;
- };
- struct queue * createQueue(int size){
- struct queue * r = (struct queue *) malloc(sizeof(struct queue));
- r-> arr = (int *) malloc(sizeof(int) * size);
- r->front = 0;
- r->back = 0;
- r->size = 0;
- r->maxSize = size;
- return r;
- }
- void deleteQueue(struct queue *q){
- free(q->arr);
- free(q);
- }
- bool isEmpty(struct queue *q){
- return q->size == 0;
- }
- bool isFull(struct queue *q){
- return q->size == q->maxSize;
- }
- int size(struct queue *q){
- return q->size;
- }
- bool enqueue(struct queue * q, int value){
- if(isFull(q)){
- printf("Cannot enqueue value '%d'to the queue. Queue full.\n", value);
- return false;
- }
- q->back ++;
- q->back %= q->maxSize;
- q->size ++;
- q->arr[ q-> back ] = value;
- if(q->size == 1) q->front = q->back;
- return true;
- }
- int dequeue(struct queue *q){
- if(isEmpty(q)){
- printf("Cannot dequeue. Queue is empty.\n");
- return -1;
- }
- int value = q->arr[ q->front ];
- q->front ++;
- q->front %= q->maxSize;
- q->size --;
- return value;
- }
- int main(){
- int n,m;
- printf("Input n m: ");
- scanf("%d%d", &n, &m);
- struct queue *q = createQueue(n);
- rep(i,n) enqueue(q, i);
- int counter = 0;
- while(size(q) > 1){
- counter++;
- int current = dequeue(q);
- if(counter != m) enqueue(q, current);
- else printf("Eliminating position %d\n", current);
- counter %= m;
- }
- printf("Left out position: %d\n", dequeue(q));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement