Skip to content

Instantly share code, notes, and snippets.

@t11a
Created January 7, 2014 12:35
Show Gist options
  • Save t11a/8298689 to your computer and use it in GitHub Desktop.
Save t11a/8298689 to your computer and use it in GitHub Desktop.
class QueueWithTwoStacks
def initialize
@s1 = []
@s2 = []
end
def enqueue(item)
@s1 << item
end
def dequeue
if @s2.empty?
while [email protected]?
@s2 << @s1.pop
end
end
@s2.pop
end
end
queue = QueueWithTwoStacks.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