Stacks
A stack is a last-in, first-out (LIFO) collection, like a stack of dishes at a buffet table or a stack of coins on your desk. You add a dish on top, and that is the first dish you take off the stack.
Tip
The classic example of a stack is the stack, which is the portion of memory on which parameters and local variables are stored. See Chapter 8 for more about the stack.
The principal methods for adding to and removing from an instance of the Stack class are Push() and Pop(); Stack also offers a Peek() method, very much like Queue. Table 16-5 shows the most important methods and properties for Stack.
Table 16-5. Stack members
Method or Property |
Purpose |
---|---|
Count |
Public property that gets the number of elements in the Stack |
Clear() |
Method that removes all objects from the Stack |
Contains() |
Method that determines if an element is in the Stack |
CopyTo() |
Method that copies the Stack elements to an existing one-dimensional array |
GetEnumerator() |
Method that returns an enumerator for the Stack |
Peek() |
Method that returns the object at the top of the Stack without removing it |
Pop() |
Method that removes and returns the object at the top of the Stack |
Push() |
Method that inserts an object at the top of the Stack |
ToArray() |
Method that copies the elements to a new array |
In Example 16-4, you rewrite Example 16-3 to use a Stack rather than a Queue. The logic is almost identical. The key difference is that a Stack is Last In, First Out, while a Queue is First ...
Get Learning C# now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.