Introduction
I was wondering why there is no possibility for a circular structure in a stack. But I wish to break this impossible thing. So I began to research to make this possible and something happened, The Circular Stack. I hope this tour on circular stack will be a great fun on the renovation of data structure.
The Circular Stack
My guess is that you are curios about what a circular stack actually does. It is just simply a dual stack. Confusing? Let me explain more that a circular stack has a super-power on the push and pop of the elements in both sides, I mean the front and back (element should pop at the side where it was actually pushed). Imagine the operation will flow as a circular queue but without compromising the stack behavior.
In our proposed structure since a circular stack actually contains a single collection that then acts as two stacks by the name Front Stack and Back Stack. Which means that the array stack occupies the entire front stack or the back stack or any composition of both stacks.
Properties
Space: The storage space
Root: The first element of the front stack
Peak: The item in the front stack that is about to pop
Deep: The item in the back stack that is about to pop
Operations
PushFront: Push an item onto the front stack that may be a top side
PushBack: Push an item onto back stack that may be the other side
PopFront: Pop an item from the front stack
PopBack: Pop an item from the back stack
Algorithm
Function Push Front:
if the Root is less than SpaceLength and Deep is less than SpaceLength
Then loop up to before Deep
Shift item to one place ahead
Place item on top
Increament Root and Deep
else PrintMessage : Full
Function Push Back
if the Root is less than SpaceLength and Deep is less than SpaceLength
Then Place the item in the Space at Deep
Increament Root and Deep
Else PrintMessage : Full
Function Pop Front
if Deep is greater than -1 and Root is not equal to -1
Top item as popped item of
Loop up to Deep element
Place space element one step before
Empty deep space element
Decrement Deep and root
return popedItem
else if Deep - 1 is not equal to Root
Then PrintMessage : FrontEmpty
else PrintMessage :Empty
return null
Function Pop Back
if Deep -1 less than SpaceLength And Deep -1 greater than Root
Deep item as poped items
Empty space at deep
Decrement deep
return popedItem
else if Root equals -1
Then PrintMessage :Empty
else PrintMessage : BackEmpty
return null
Code snippet
Conclusion
Since the proposed circular stack structure can allocate and access the pushed item over the circular structure and provide a two-way assessment on a single stack.