Circular Buffer Insert

Code

#include <stdio.h>
#include <stdint.h>

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

void insert_circular(CircularBuffer_t *cb, int value){
    if(cb->count < cb->capacity){
        cb->buffer[cb->count] = value; 
        cb->head++; 
        cb->count++; 
    }
}

int main(){
    int n,k; // k: so phan tu cho vao, n: dung luong max 
    scanf("%d%d",&n ,&k); 
    CircularBuffer_t cb = {.head = 0, .tail = 0, .count = 0, .capacity = n}; 
    int value; 

    for(int i = 0; i<k; i++){
        scanf("%d",&value); 
        insert_circular(&cb, value); 
    }
    
    for(int i = 0; i<cb.count; i++){
        printf("%d ",cb.buffer[i]); 
    }
    return 0;
}  

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 5 10 20 30 40 50

Expected Output

10 20 30 40 50