栈,特点先入后出,FILO,python中列表即为栈的实现,append方法相当于入栈,pop方法相当于出栈
python中有的队列工具,collections.deque,queue.Queue
python实现队列
class MyQueue
class MyQuene:
def __init__(self, capacity):
self.list = [None]* capacity
self.front = 0
self.rear = 0
def enqueue(self, element):
if (self.rear+1) % len(self.list) == self.front:
raise Exception("queue is full")
self.list[self.rear] = element
self.rear = (self.rear+1) % len(self.list)
def dequeue(self):
if self.rear == self.front:
raise Exception("queue is empty")
dequeue_element = self.list[self.front]
self.front = (self.front+1)%len(self.list)
return dequeue_element
def output(self):
i = self.front
while i != self.rear:
print(self.list[i])
i = (i+1)%len(self.list)
网友评论