Created
April 25, 2015 01:59
-
-
Save davissp14/86b32aa86f3e79c2b566 to your computer and use it in GitHub Desktop.
Queue using a fixed size array
This file contains hidden or 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 Queue | |
def initialize(size=10) | |
raise 'InvalidInputType' unless size.is_a?(Fixnum) | |
@store = Array.new(size) | |
@size = size | |
@tail = @head = 0 | |
end | |
def enqueue(ele) | |
raise "Overflow" if full? | |
@store[@tail] = ele | |
if @tail == @size - 1 | |
@tail = 0 | |
else | |
@tail += 1 | |
end | |
end | |
def dequeue | |
raise "Underflow" if empty? | |
result = @store[@head] | |
@store[@head] = nil | |
if @head == @size - 1 | |
@head = 0 | |
else | |
@head += 1 | |
end | |
result | |
end | |
def empty? | |
@head == @tail | |
end | |
def full? | |
@head == @tail + 1 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment