Last active
February 12, 2021 18:37
-
-
Save yovasx2/358d92993dcdd9b5e178ae4961b83943 to your computer and use it in GitHub Desktop.
screening interview: queue using restricted size arrays
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
# Build a queue class with the enqueue and dequeue methods. | |
# The queue can store an *UNLIMITED* number of elements but you are limited to using arrays that can store up to 5 elements max | |
# 1# [3,4,5] 2# [6,7,8,9,10] 3# [11,12,13] | |
# [1#, 2#, 3#, 4#, 5#] [6#, ] | |
class Node | |
SIZE_LIMIT = 5.freeze | |
attr_accessor :value | |
attr_accessor :_next | |
attr_accessor :size | |
def initialize | |
@value = [] | |
@_next = nil | |
@size = 0 | |
end | |
def insert(val) | |
return false if @value.size == SIZE_LIMIT | |
@value << val | |
@size += 1 | |
return true | |
end | |
def get_element() | |
return [ @value.shift, @_next ] | |
end | |
end | |
class Queue | |
attr_accessor :head | |
attr_accessor :tail | |
def initialize() | |
@head = Node.new | |
@tail = @head | |
end | |
def dequeue() | |
result = @head.get_element | |
element = result[0] | |
_next = result[1] | |
while !element && _next | |
@head = @head._next | |
result = @head.get_element | |
element = result[0] | |
_next = result[1] | |
end | |
puts element | |
return element | |
end | |
def enqueue(val) | |
result = @tail.insert(val) | |
unless result | |
@tail._next = Node.new | |
@tail = @tail._next | |
@tail.insert(val) | |
end | |
end | |
end | |
q = Queue.new() | |
q.enqueue(1) # => true | |
q.enqueue(2) # => true | |
q.enqueue(3) # => true | |
q.enqueue(4) # => true | |
q.enqueue(5) # => true | |
q.enqueue(6) # => true | |
q.dequeue()# => 1 | |
q.dequeue() # => 2 | |
q.dequeue() # => 3 | |
q.dequeue() # => 4 | |
q.dequeue() # => 5 | |
q.dequeue() # => 6 | |
q.dequeue() # => nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment