Skip to content

Instantly share code, notes, and snippets.

@t11a
Created January 7, 2014 12:34
Show Gist options
  • Save t11a/8298669 to your computer and use it in GitHub Desktop.
Save t11a/8298669 to your computer and use it in GitHub Desktop.
class QueueWithSingleStack
def initialize
@stack = []
end
def enqueue(item)
@stack << item
end
def dequeue
if @stack.empty?
return nil
else
return recurse()
end
end
def recurse
top = @stack.pop
if @stack.empty?
return top
else
item = recurse
@stack << top
return item
end
end
end
queue = QueueWithSingleStack.new
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
p queue.dequeue # => 1
p queue.dequeue # => 2
queue.enqueue(5)
p queue.dequeue # => 3
p queue.dequeue # => 4
p queue.dequeue # => 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment