in reply to using foreach
Indeed, it is not a good idea to manipulate a stack unless you follow the specific interface that applies to a stack:
In your code, I do not see any place where you check for the empty stack, so in another context (where it's not obvious that there are items on the stack), it would be a potential error to attempt to pop from a potentially empty stack.
While it is true that a "while loop" is would act in this capacity, you have used a "for loop", and should therefore check for empty prior to a pop.
|
|---|