Created
January 7, 2014 12:35
-
-
Save t11a/8298689 to your computer and use it in GitHub Desktop.
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 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