Class: Containers::Queue

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/containers/queue.rb

Overview

A Queue is a container that keeps elements in a first-in first-out (FIFO) order. Because of its

properties, it is often used as a buffer.

This implementation uses a doubly-linked list, guaranteeing O(1) complexity for all operations.

Instance Method Summary collapse

Constructor Details

#initialize(ary = []) ⇒ Queue

Create a new queue. Takes an optional array argument to initialize the queue.

q = Containers::Queue.new([1, 2, 3])
q.pop #=> 1
q.pop #=> 2


17
18
19
# File 'lib/containers/queue.rb', line 17

def initialize(ary=[])
  @container = Containers::Deque.new(ary)
end

Instance Method Details

#each(&block) ⇒ Object

Iterate over the Queue in FIFO order.



64
65
66
# File 'lib/containers/queue.rb', line 64

def each(&block)
  @container.each_forward(&block)
end

#empty?Boolean

Returns true if the queue is empty, false otherwise.

Returns:

  • (Boolean)


59
60
61
# File 'lib/containers/queue.rb', line 59

def empty?
  @container.empty?
end

#nextObject

Returns the next item from the queue but does not remove it.

q = Containers::Queue.new([1, 2, 3])
q.next #=> 1
q.size #=> 3


26
27
28
# File 'lib/containers/queue.rb', line 26

def next
  @container.front
end

#popObject

Removes the next item from the queue and returns it.

q = Containers::Queue.new([1, 2, 3])
q.pop #=> 1
q.size #=> 2


46
47
48
# File 'lib/containers/queue.rb', line 46

def pop
  @container.pop_front
end

#push(obj) ⇒ Object Also known as: <<

Adds an item to the queue.

q = Containers::Queue.new([1])
q.push(2)
q.pop #=> 1
q.pop #=> 2


36
37
38
# File 'lib/containers/queue.rb', line 36

def push(obj)
  @container.push_back(obj)
end

#sizeObject

Return the number of items in the queue.

q = Containers::Queue.new([1, 2, 3])
q.size #=> 3


54
55
56
# File 'lib/containers/queue.rb', line 54

def size
  @container.size
end