Your Stack
is not written in a way that facilitates clean OO re-use: you haven't got a virtual destructor, and the member functions that derived types may wish to override aren't virtual either (specifically push
and pop
). So, it is cleaner to write a new class that uses Composition - storing a Stack
object as a data member. Then there's no need to change Node
- you can just add a Stack<Node*>
to your StackWithMin
class, and push/pop an extra Node*
only when the data Stack
pushes/pops a Node
that changes the min. For example, after pushing 3, 7, 5, 2, 3, your StackWithMin
data members would be:
Stack<Data> Stack<Node*>
[0] 3 &[0]
[1] 7 &[3]
[2] 5
[3] 2
[4] 3
This encodes that the current min is at &[3]
, and if a pop removes that element then it should be popped from the Stack<Node*>
too.
Separately, Node
is a supporting type for Stack
, and the definition need not be offered as part of the client-facing interface. To hide it, consider putting it in a namespace called something like Stack_Private
, Stack_Support
or Stack_Implementation
so that clients know not to use, then you can reasonably make it a struct
and get/set the data members directly instead of using accessor functions - that will make your code less verbose.