Created
September 27, 2018 14:30
-
-
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.
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
#!/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