is the stack implementation correct?
nandinicbit1981 opened this issue · 1 comments
Hello,
Firstly, great work on documentation, its just perfect!
I am reading through the datastructure examples and i dont quite understand the stack implementation.
I do understand you are using an array to implement stack. But everytime we do a pop() operation, shouldn't the array element be actually removed and array size altered? Otherwise, even after doing a pop() operation the memory will still be allocated for the popped element.
Some explanation would be great! thanks!
You are correct that the memory is still allocated for the popped element. This is by design, as the Stack get's an initial capacity
size, and the array will forever be of that size. The array is never resized, and if we try to put
more elements than capacity
we'll get a RuntimeException("Stack is full")
.
If you want to reclaim memory, it's best to implement a stack using a linked list, allowing to easily add/remove memory.