A "stack" is an ordered collection of items. Items can be "pushed" onto the end of the stack, and "popped" from that same end of the stack. The item at the end of the stack can be "peeked" at (identified without removing it from the stack), and the "size" of the stack can be identified at any time. Also, the stack can be identified as being "empty" (a size of 0).
A common analogy is that of placing books in a single pile on a desk. Placing a book on the desk is a "push" operation. Placing another book on top of that is a "push" operation. Placing one more is another "push", and now the size of the stack is 3. The statement "isEmpty" is false at this point. You can "peek" at the stack to see the book on top, but none of the books underneath are visible. A single "pop" operation removes the top book from the stack, and two additional pop operations will return the stack to its empty state, where the "size" is 0 and "isEmpty" is true.
Because of the way items are pushed and popped on a stack, it is sometimes called a Last In-First Out (LIFO) structure.
Create a file atds.py
(Advanced Topics Data Structures) that will be used to collect a number of important ADT (Abstract Data Type) implementations. The first component of this file is a class description for a Stack
class.
The Stack
class will use a list to manage a stack of items, and include:
push(item)
method to push an item onto the stackpop()
method to remove an item from the stack, and return that removed item as a resultpeek()
method which returns the value of the top item in the stacksize()
method which returns the number of items in the stackisEmpty()
method which returns True
or False
, depending on the state of the stack