Because the standard list collection has both a head and a tail, it is easy to create a derived list collection that mimics the behavior of a last-in-first-out stack. A stack is like a stack of trays in a cafeteria. As trays are added to the stack, they go on top of the stack. The last tray added is the first to be removed. The list collection member functions AddHead and RemoveHead can be used to add and remove elements specifically from the head of the list; thus the most recently added element is the first to be removed.
·To create a stack collection:
Derive a new list class from one of the existing list classes provided with the Foundation library and add more member functions to support the functionality of stack operations.
The following example shows you can add member functions to push elements on to the stack, peek at the top element of the stack, and pop the top element from the stack:
class CTray : public CObject { ... };
class CStack : public CObList
{
public:
// add element to top of stack
void Push( CTray* newTray )
{ AddHead( newTray ); }
// peek at top element of stack
CTray* Peek()
{ return IsEmpty() ? NULL : (CTray*)GetHead(); }
// pop top element off stack
CTray* Pop()
{ return (CTray*)RemoveHead(); }
};