python数据结构之双端队列
双端队列(deque,全名double-ended queue),是一种具有队列和栈的性质的数据结构。双端队列中的元素可以从两端弹出,其限定插入和删除操作在表的两端进行。双端队列可以在队列任意一端入队和出队。
class DoubleEndedQueue(object):
"""双端队列"""
def __init__(self):
self.__item = []
def is_empty(self):
"""判断队列是否为空"""
return self.__item == []
def size(self):
"""返回队列大小"""
return self.__item.__len__()
def add_head(self, item):
"""在队头添加元素"""
self.__item.insert(0, item)
def add_tail(self, item):
"""在队尾添加元素"""
self.__item.append(item)
def pop_head(self):
"""从队头删除元素"""
return self.__item.pop()
def pop_tail(self):
"""从队尾删除元素"""
return self.__item.pop(0)
if __name__ == "__main__":
deque = DoubleEndedQueue()
print(deque.is_empty())
print(deque.size())
deque.add_head(100)
deque.add_head(200)
deque.add_head(300)
print(deque.is_empty())
print(deque.size())
print(deque.pop_head())
print(deque.pop_head())
print(deque.pop_head())
deque.add_tail(400)
deque.add_tail(500)
deque.add_tail(600)
print(deque.pop_tail())
print(deque.pop_tail())
print(deque.pop_tail())