Stack
A stack is another container that is very
similar to the queue. You just use different methods to access the
stack. The item that is added last to the stack is read first. The
stack is a last in, first out (LIFO)
container.
Figure 10-2
shows the representation of a stack where the Push() method adds an item to the stack, and the
Pop() method gets the item that was
added last.
Similar to the queue classes, the nongeneric
Stack class implements the interfaces
ICollection, IEnumerable, and ICloneable; the generic Stack<T> class implements the interfaces
IEnumerable<T>, ICollection, and IEnumerable.
Members of the Stack and
Stack<T> class are listed in the
following table.
In this example, three items are added to the stack
with the Push() method. With the
foreach method, all items are iterated
using the IEnumerable interface. The
enumerator of the stack does not remove the items; it just returns
item by item.
Because the items are read in the order from the
last added to the first, the following result is produced:
Reading the items with the enumerator does not
change the state of the items. With the Pop() method, every item that is read is also
removed from the stack. This way that you can iterate the
collection using a while loop and verify
the Count property if items are still
existing:
The result gives two times CBA. After the second
iteration, the stack is empty because the second iteration used the
Pop() method: