一、循环队列的实现
代码解释
1、完成初始化
2、定义方法
3、测试实例
4、完整代码
class AQueue :
def __init__ ( self, size= 10 ) :
self. __mSize = size
self. __front= 0
self. __rear = 0
self. __listArray = [ None] * size
#清空元素
def clear ( self) :
self. __front = 0
self. __rear = 0
for i in range ( self. __mSize) :
self. __listArray[ i] = None
# 入队操作
def enqueue ( self, item) :
if not self. is_full ( ) :
self. __rear= ( self. __rear+ 1 ) % self. __mSize
self. __listArray[ self. __rear] = item
elif self. is_full ( ) :
raise ValueError ( "Queue is Full." )
# 出队操作
def dequeue ( self) :
if not self. is_empty ( ) :
self. __front= ( self. __front+ 1 ) % self. __mSize
self. item= self. __listArray[ self. __front]
self. __listArray[ self. __front] = None
return self. item
elif self. is_empty ( ) :
raise ValueError ( "Queue is empty." )
# 判空,检查队列是否为空
def is_empty ( self) :
return self. __front== self. __rear
# 判满,注意并不是所有的位置都有元素才是满,当只有一个是None时就满了,有点像链表的哑结点
def is_full ( self) :
return ( ( self. __rear+ 1 ) % self. __mSize== self. __front)
def __repr__ ( self) : # 显示队列中所有元素,数组切片左闭右开
return str ( self. __listArray[ : self. __mSize] )
if __name__== '__main__' :
queue= AQueue ( 5 )
queue. enqueue ( 1 )
print ( queue)
print ( queue. dequeue ( ) )
queue. enqueue ( 2