Created
May 27, 2016 19:52
-
-
Save ramfjord/340296cb6d9ca1fd4b2d4acbf8070df9 to your computer and use it in GitHub Desktop.
Simple Ruby Queue
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
class MyQ | |
def initialize | |
@head = @tail = [] | |
end | |
def enq(obj) | |
@tail << obj << [] # must use methods that mutate the array here | |
@tail = @tail[1] | |
obj | |
end | |
def deq | |
raise "queue is empty" if empty? | |
obj = @head[0] | |
@head = @head[1] | |
obj | |
end | |
def empty? | |
@head.empty? # @head == @tail would be slower | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment