Created
November 18, 2016 20:00
-
-
Save arjans/2bb69dba3f01d26844a6a52767a6c7f1 to your computer and use it in GitHub Desktop.
Queue in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Implementing a queue for algorithm study group. | |
class Queue | |
def initialize | |
@front = 0 | |
@back = 0 | |
@items = [nil, nil, nil, nil] | |
@num_items = 0 | |
end | |
def empty? | |
@num_items == 0 | |
end | |
def dequeue | |
if empty? | |
"Underflow" | |
else | |
@num_items -= 1 | |
item = @items[@front] | |
@items[@front] = nil | |
@front = (@front + 1) % @items.length | |
puts @items.inspect | |
item | |
end | |
end | |
def enqueue(x) | |
if @num_items == @items.length | |
"Overflow" | |
else | |
@num_items += 1 | |
@items[@back] = x | |
@back = (@back + 1) % @items.length | |
@items | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment