LIFO
(
Last In First Out
) queues are more frequently called
stacks
. Think of a stack
of papers where you can only access the top-most paper. You can put another paper
on top of the stack, making it the new top-most paper, or you can take the top-most
paper away to reveal the one beneath it.
Traditionally, the operations on stacks are named push and pop, but the Python
queue
module uses the exact same API as for FIFO queues:
put()
and
get()
.
However, in a LIFO queue, these methods operate on the "top" of the stack instead
of at the front and back of a line. This is an excellent example of polymorphism. If you
look at the
Queue
source code in the Python standard library, you'll actually see that
there is a superclass with subclasses for FIFO and LIFO queues that implement the
few operations (operating on the top of a stack instead of front and back of a
deque
instance) that are critically different between the two.
Here's an example of the LIFO queue in action:
>>> from queue import LifoQueue
>>> stack = LifoQueue(maxsize=3)
>>> stack.put("one")
>>> stack.put("two")
>>> stack.put("three")
>>> stack.put("four", block=False)
Traceback (most recent call last):
File "", line 1, in
stack.put("four", block=False)
File "/usr/lib64/python3.3/queue.py", line 133, in put
raise Full
queue.Full
>>> stack.get()
'three'
>>> stack.get()
www.it-ebooks.info
Python Data Structures
[
186
]
'two'
>>> stack.get()
Do'stlaringiz bilan baham: |