LeetCode迴圈佇列的實現
阿新 • • 發佈:2018-12-26
寫了好久終於把邏輯理順了,刪刪減減的註釋沒寫多少。不過作為新手還是很欣慰
class MyCircularQueue(object):
# 設定定義傳進來的引數K,也就是佇列最大值,然後頭指標,尾指標,建立一個內部都為空且最大為K+1的列表
def __init__(self, k):
self.queue = [None] * k # 空列表
self.maxsize = k + 1 # 最大值
self.head = 0 # 頭指標
self.tial = 0 # 尾指標
self. tag = 0 # 新增識別符號,判斷佇列空滿狀態
def enQueue(self, value):
# 判斷列表空滿狀態,不滿就進行插入,並讓頭指標為0,尾指標向下移動一位
if (self.isFull() == -1):
# print('列表滿')
self.tag = 1
return
if (self.isEmpty() == True):
# print('列表為空')
self.queue[self.tial] = value
self.tial = (self.tial + 1) % self.maxsize
self.tag = 1
return
self.queue[self.tial] = value
self.tial = (self.tial + 1) % self.maxsize
self.tag = 1
def deQueue(self):
# 判斷列表是否為空
if (self.isEmpty() == True):
print ('佇列為空,無法判定!')
self.tag = 0
return
data = self.queue[self.head] # 保留的火種,可能有用
self.queue[self.head] = None
self.head = (self.head + 1) % self.maxsize
if self.head == self.tial:
self.tag = 0
return
def Front(self):
# 判斷列表是否為空
if (self.isEmpty() == True):
print('佇列為空,沒法取出來!')
self.tag = 0
return -1
else:
data = self.queue[self.head]
self.queue[self.head] = None
self.head = (self.head + 1) % self.maxsize
self.tag = 1
if self.head != self.tial:
return data
else:
self.tag = 0
return '佇列空'
def Rear(self):
# 判斷列表是否為空
if (self.isFull() == 0):
print('佇列為空,沒法取出來!')
return -1
else:
data = self.queue[self.tial - 1]
self.queue[self.tial - 1] = None
self.tial = (self.tial - 1) % self.maxsize
return data
def isFull(self):
if (self.tag == 1) and ((self.tial + 1) % self.maxsize == self.head):
# print('佇列為滿')
return -1
else:
# print('佇列非滿')
return 1
def isEmpty(self):
if (self.tag == 0) and (self.tial == self.head):
return True
obj = MyCircularQueue(4)
# param_1 = obj.enQueue(1)
for i in range(4):
obj.enQueue(i)
print(obj.queue)
# param_2 = obj.deQueue()
for i in range(4):
obj.deQueue()
print(obj.queue)
# param_3 = obj.Front()
print(obj.Front())
# param_4 = obj.Rear()
print(obj.Rear())
# param_5 = obj.isEmpty()
# print(obj.isEmpty())
# param_6 = obj.isFull()
# print(obj.isFull())