Skip to content

Instantly share code, notes, and snippets.

@woodRock
Created September 27, 2018 14:30
Show Gist options
  • Save woodRock/2367913b62485dda4b6c4b39619def7b to your computer and use it in GitHub Desktop.
Save woodRock/2367913b62485dda4b6c4b39619def7b to your computer and use it in GitHub Desktop.
Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure with the following methods: enqueue, which inserts an element into the queue, and dequeue, which removes it.
#!/usr/bin/env ruby
class Queue
def initialize
@s1,@s2 = [],[]
end
def enqueue e
while not @s1.empty?
@s2 << @s1.last()
@s1.pop()
end
@s1 << e
while not @s2.empty?
@s1 << @s2.last()
@s2.pop()
end
end
def dequeue
puts "Q is empty!" if @s1.empty?
@s1.pop()
end
alias << enqueue
alias pop dequeue
end
q = Queue.new()
q << 'e'
q << 'f'
q << 'g'
p q.pop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment