Design and implement a circular stack. A circular stack is similar to a regular stack, but the underlying array is used in a circular manner. The operations push, pop, top (peek), and isEmpty should be supported.
Input:
Operations: ["push(1)","push(2)","top()","pop()","isEmpty()"]Output:
[null,null,2,2,false]Explanation:
- push(1) adds 1 to the stack.- push(2) adds 2 to the stack.- top() returns the current top element, which is2.- pop() removes and returns the current top element, which is2.- isEmpty() returns false as the stack is not empty.
A stack follows the Last In First Out (LIFO) principle. By using a circular array to implement a stack, we can efficiently manage the stack operations by utilizing a circular buffer.
Here is the approach:
Use an array to store the elements.
Use an integer top to keep track of the index of the most recently added element.
If top reaches the end of the array, it wraps around to the beginning (circular logic).
Here are the operations:
Circular Array: The array is considered circular, meaning that if the end of the array is reached, it wraps around to the beginning.
Push Operation: Inserts an element at the next available position considering the circular nature of the array.
Pop Operation: Removes the most recently added element considering the circular nature of the array.
Top Operation: Retrieves the most recently added element without removing it.
isEmpty Operation: Checks if the stack is empty.
isFull Operation: Checks if the stack is full.
Static Capacity: The stack has a fixed capacity and will not resize.