All submissions

Circular Buffer Insert

Insert only one element at current head.

#include <stdio.h>

typedef struct {
    int buffer[100];
    int head;
    int tail;
    int count;
    int capacity;
} CircularBuffer;

void insert_circular(CircularBuffer *cb, int value) {
    // Your logic using only pointer access
    if(cb->count != cb->capacity){      //inverted logic for insertion
        cb->head %= 100;                //wrap around
        cb->buffer[cb->head] = value;   //insertion
        cb->head++;                     //head increment for next
        cb->count++;                    //count of elements is increased
    }
}

int main() {
    int n, k;
    scanf("%d %d", &n, &k);

    CircularBuffer cb = { .head = 0, .tail = 0, .count = 0, .capacity = n };

    for (int i = 0; i < k; i++) {
        int val;
        scanf("%d", &val);
        insert_circular(&cb, val);
    }

    for (int i = 0; i < cb.count; i++) {
        printf("%d", cb.buffer[i]);
        if(i < cb.count-1){
           printf(" "); 
        }
    }

    return 0;
}

Solving Approach

wrap head around using % 100 . then insert at current head, increment count and head.
check for capacity and count equality at the beginning.

 

 

Loading...

Input

5 5 10 20 30 40 50

Expected Output

10 20 30 40 50