Created
January 7, 2014 12:34
-
-
Save t11a/8298669 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 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