Queue/Definition: Difference between revisions

From Rosetta Code
Content added Content deleted
(Append to one side, pop from the other)
Line 21: Line 21:
from collections import deque
from collections import deque
fifo = deque()
fifo = deque()
fifo.append(value) # push
fifo. appendleft(value) # push
value = fifo.pop()
value = fifo.pop()
not fifo # empty
not fifo # empty

Revision as of 20:41, 4 November 2007

Task
Queue/Definition
You are encouraged to solve this task according to the task description, using any language you may know.

Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion.

Operations:

  • push - add element
  • pop - pop first element
  • empty - return truth value when empty

Errors:

  • handle the error of trying to pop from an empty queue (behavior depends on the language and platform)

Define the data structure for a FIFO element. Said element should contain a data member capable of holding a numeric value, and the link to the next element should be mutable.

Python

Python 2.4 and later includes a deque class, supporting thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction. For other options see Python Cookbook.

from collections import deque
fifo = deque()
fifo. appendleft(value) # push
value = fifo.pop()
not fifo # empty
fifo.pop() -> raises IndexError when empty