struct CircularBuffer {
int* buffer;
int size;
int head;
int tail;
int count;
};
//initialize the circular buffer
void init(CircularBuffer* cb, int size) {
cb->buffer = new int[size];
cb->size = size;
cb->head = 0;
cb->tail = 0;
cb->count = 0;
}
//get the number of items in the circular buffer
int count(CircularBuffer* cb) {
return cb->count;
}
//check if the circular buffer is empty
bool isEmpty(CircularBuffer* cb) {
return cb->count == 0;
}
//check if the circular buffer is full
bool isFull(CircularBuffer* cb) {
return cb->count == cb->size;
}
//delete the circular buffer
void deleteCB(CircularBuffer* cb) {
delete[] cb->buffer;
}
//push item to circular buffer
void push(CircularBuffer* cb, int item) {
if (isFull(cb)) {
cout << "Buffer is full" << endl;
return;
}
cb->buffer[cb->head] = item;
cb->head = (cb->head + 1) % cb->size;
cb->count++;
}
//pop item from circular buffer
int pop(CircularBuffer* cb) {
if (isEmpty(cb)) {
cout << "Buffer is empty" << endl;
return -1;
}
int item = cb->buffer[cb->tail];
cb->tail = (cb->tail + 1) % cb->size;
cb->count--;
return item;
}
//print the circular buffer items form head to tail
void print(CircularBuffer* cb) {
if (isEmpty(cb)) {
cout << "Buffer is empty" << endl;
return;
}
int i = cb->tail;
while (i != cb->head) {
cout << cb->buffer[i] << " ";
i = (i + 1) % cb->size;
}
cout << endl;
}
void test_circular() {
CircularBuffer cb;
init(&cb, 5);
push(&cb, 1);
push(&cb, 2);
push(&cb, 3);
push(&cb, 4);
push(&cb, 5);
print(&cb);
cout << "count: " << count(&cb) << endl;
cout << "pop: " << pop(&cb) << endl;
print(&cb);
cout << "count: " << count(&cb) << endl;
cout << "pop: " << pop(&cb) << endl;
print(&cb);
cout << "count: " << count(&cb) << endl;
cout << "pop: " << pop(&cb) << endl;
print(&cb);
cout << "count: " << count(&cb) << endl;
cout << "pop: " << pop(&cb) << endl;
print(&cb);
cout << "count: " << count(&cb) << endl;
cout << "pop: " << pop(&cb) << endl;
print(&cb);
push(&cb, 50);
cout << "push: " << 50 << endl;
cout << "count: " << count(&cb) << endl;
print(&cb);
cout << "count: " << count(&cb) << endl;
cout << "pop: " << pop(&cb) << endl;
print(&cb);
}
int main(int argc,char* argv[]) {
test_circular();
}