Class: BasicQueue::Queue
- Inherits:
-
Object
- Object
- BasicQueue::Queue
- Defined in:
- lib/basic_queue.rb
Overview
Instance Method Summary collapse
-
#<<(item) ⇒ Item
Adds new item to the queue.
-
#clear ⇒ Boolean
Clears queue.
-
#deq ⇒ Item
Removes and returns the item on this queue that was least recently added.
-
#empty? ⇒ Boolean
Checks whether the queue is empty or not.
-
#enq(item) ⇒ Item
Adds new item to the queue.
-
#initialize ⇒ Queue
constructor
Initializes the queue and sets variables.
-
#length ⇒ Integer
Returns length of queue.
-
#peek ⇒ Item
Returns next item in the queue.
-
#size ⇒ Object
Returns length of queue.
Constructor Details
#initialize ⇒ Queue
Initializes the queue and sets variables.
24 25 26 27 28 |
# File 'lib/basic_queue.rb', line 24 def initialize @length = 0 @first = nil @last = nil end |
Instance Method Details
#<<(item) ⇒ Item
Adds new item to the queue. Alias method for #enq().
55 56 57 |
# File 'lib/basic_queue.rb', line 55 def <<(item) enq(item) end |
#clear ⇒ Boolean
Clears queue.
85 86 87 88 89 90 |
# File 'lib/basic_queue.rb', line 85 def clear @length = 0 @first = nil @last = nil true end |
#deq ⇒ Item
Removes and returns the item on this queue that was least recently added.
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/basic_queue.rb', line 61 def deq return nil if empty? # save previous first node for return value old_first = @first # update first node @first = @first.next_node @length -= 1 # avoid loitering @last = nil if empty? old_first.item end |
#empty? ⇒ Boolean
Checks whether the queue is empty or not.
106 107 108 |
# File 'lib/basic_queue.rb', line 106 def empty? length == 0 end |
#enq(item) ⇒ Item
Adds new item to the queue.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/basic_queue.rb', line 33 def enq(item) # save previous old last node for use below old_last = @last # create new last node and update @last_item @last = Node.new(item, nil) if empty? # set to nil @first = @last else # point 2nd last node to last node old_last.next_node = @last end @length += 1 item end |
#length ⇒ Integer
Returns length of queue.
94 95 96 |
# File 'lib/basic_queue.rb', line 94 def length @length end |
#peek ⇒ Item
Returns next item in the queue.
79 80 81 |
# File 'lib/basic_queue.rb', line 79 def peek empty? ? nil : @first.item end |
#size ⇒ Object
Returns length of queue. Alias method for #length.
100 101 102 |
# File 'lib/basic_queue.rb', line 100 def size length end |