# 出队 def deQueue return false if is_empty? data = @queue[@head] @queue[@head] = 0 @head = (@head+1) % @Maxsize return data end
# 获取队首 def front return -1 if is_empty? return @queue[@head] end # 获取队尾 def rear return -1 if is_empty? return @queue[@last-1] end # 判空 def is_empty? if @head == @last return true else return false end end
# 判满 def is_full? if (@last + 1) % @Maxsize == @head return true else return false end end end
=begin Initialize your data structure here. Set the size of the queue to be k. :type k: Integer =end attr_accessor :head, :last, :Maxsize def initialize(k) @Maxsize = k+1 @head = 0 @last = 0 @queue = Array.new(@Maxsize) end =begin Insert an element into the circular queue. Return true if the operation is successful. :type value: Integer :rtype: Boolean =end def en_queue(value) return false if is_full @queue[@last] = value @last = (@last+1) % @Maxsize
return true end =begin Delete an element from the circular queue. Return true if the operation is successful. :rtype: Boolean =end def de_queue() return false if is_empty data = @queue[@head] @queue[@head] = 0 @head = (@head+1) % @Maxsize return true end =begin Get the front item from the queue. :rtype: Integer =end def front() return -1 if is_empty return @queue[@head] end =begin Get the last item from the queue. :rtype: Integer =end def rear() return -1 if is_empty return @queue[@last-1] end
=begin Checks whether the circular queue is empty or not. :rtype: Boolean =end def is_empty() if @head == @last return true else return false end end =begin Checks whether the circular queue is full or not. :rtype: Boolean =end def is_full() if (@last + 1) % @Maxsize == @head return true else return false end end end
Post title:Ruby实现循环队列(CircularQueue)
Post author:Varsion
Create time:2020-08-04 17:09:14
Post link:https://blog.varsion.cn/post/58d59d5e.html
Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.