educative.io

Pop() implementation using arrays

Hi,

Regarding the pop() implementation mentioned in the course:

Lets say their is only 1 element in the stack (so as in the array), when I call pop() on the stack the implementation returns the element pointed by “top” variable and decrements it.

Statement is:

return array[top–];

but this only changes the value of the “top” variable by setting it to -1(from 0) and never removes the element from the array.

But, when I verified this by printing the backed array, the element at index 0 was set to value 0.

How come it deletes the value in the backed array? (as there is no replacement logic anywhere)

Thank you.

Regards,
Puneeth

In the pop() method of the Stack class you provided, the line return array[top--]; has two actions:

  1. It returns the value at the current top index.
  2. It decrements the top variable, effectively “removing” the element from the logical perspective of the stack.

However, it’s important to note that the actual value in the array at the index top is not explicitly removed or cleared. The decrement of the top variable means that the next push operation will overwrite this value when a new element is added to the stack.

In other words, the value in the array at index top is effectively considered “removed” because the top variable is decremented, making that index no longer part of the active portion of the stack. The array still contains the old value, but it is no longer considered part of the stack.

If you were to print the array after several push and pop operations, you would see that only elements up to the current top index are actively used, and elements beyond that point are essentially “ignored” until new elements are pushed onto the stack. The pop() operation, by decrementing top, logically excludes the top element from future stack operations.