#K48682. Circular Buffer
Circular Buffer
Circular Buffer
Implement a circular buffer data structure that supports the following operations:
write X
: Write an integer X into the buffer. If the buffer is full, printBuffer is full
and do not add X.read
: Remove and print the oldest element in the buffer. If the buffer is empty, printBuffer is empty
.overwrite X
: If the buffer is full, overwrite the oldest element with X. If the buffer is not full, simply add X.clear
: Clear the buffer, making it empty.get
: Print the current contents of the buffer as space-separated values. If the buffer is empty, printEmpty
.empty
: PrintTrue
if the buffer is empty, otherwise printFalse
.
The circular buffer works in a first-in-first-out (FIFO) order and has a fixed capacity. All commands are provided via standard input, and you should process them in the order given. Any error (such as trying to write to a full buffer) should result in printing the specified error message.
Note on Exceptions: When executing a write
command on a full buffer, output the message "Buffer is full". Similarly, attempting to read
from an empty buffer should output "Buffer is empty".
inputFormat
The first line contains two integers (N) and (M), where (N) is the size of the circular buffer and (M) is the number of operations. Each of the following (M) lines contains a command. The commands can be:
write X
: Write integer (X) into the buffer. If the buffer is full, print "Buffer is full".read
: Remove and print the oldest element in the buffer. If the buffer is empty, print "Buffer is empty".overwrite X
: If the buffer is full, remove the oldest element and insert (X); otherwise, add (X) normally.clear
: Clear the buffer.get
: Print the current contents of the buffer as space-separated integers. If the buffer is empty, print "Empty".empty
: Print "True" if the buffer is empty, otherwise print "False".
Each command that produces output should have its result printed on a new line.
outputFormat
Print the results of the commands that require an output (namely, read
, get
, empty
, or error messages from write
) in the order they occur, each on a new line. The output format must strictly match the expected output.## sample
3 8
write 1
write 2
get
read
get
write 3
write 4
get
1 2
1
2
2 3 4
</p>