Class: BasicQueue::Queue

Inherits:
Object
  • Object
show all
Defined in:
lib/basic_queue.rb

Overview

See Also:

Author:

  • Robert Sedgewick

  • Kevin Wayne

  • Michael Imstepf

Instance Method Summary collapse

Constructor Details

#initializeQueue

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().

Parameters:

  • item (Item)

    the item to be enqueued

Returns:

  • (Item)

    item



55
56
57
# File 'lib/basic_queue.rb', line 55

def <<(item)
  enq(item)
end

#clearBoolean

Clears queue.

Returns:

  • (Boolean)

    true



85
86
87
88
89
90
# File 'lib/basic_queue.rb', line 85

def clear
  @length = 0
  @first = nil
  @last = nil
  true    
end

#deqItem

Removes and returns the item on this queue that was least recently added.

Returns:

  • (Item)

    dequeued item



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.

Returns:

  • (Boolean)


106
107
108
# File 'lib/basic_queue.rb', line 106

def empty?
  length == 0
end

#enq(item) ⇒ Item

Adds new item to the queue.

Parameters:

  • item (Item)

    the item to be enqueued

Returns:

  • (Item)

    item



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

#lengthInteger

Returns length of queue.

Returns:

  • (Integer)


94
95
96
# File 'lib/basic_queue.rb', line 94

def length
  @length
end

#peekItem

Returns next item in the queue.

Returns:

  • (Item)

    item



79
80
81
# File 'lib/basic_queue.rb', line 79

def peek
  empty? ? nil : @first.item
end

#sizeObject

Returns length of queue. Alias method for #length.



100
101
102
# File 'lib/basic_queue.rb', line 100

def size
  length
end