Python - 双端队列

双端队列支持从任一端添加和删除元素。 更常用的堆栈和队列是双端队列的退化形式,其中输入和输出仅限于一个端点。


示例

import collections

DoubleEnded = collections.deque(["Mon","Tue","Wed"])
DoubleEnded.append("Thu")

print ("Appended at right - ")
print (DoubleEnded)

DoubleEnded.appendleft("Sun")
print ("Appended at right at left is - ")
print (DoubleEnded)

DoubleEnded.pop()
print ("Deleting from right - ")
print (DoubleEnded)

DoubleEnded.popleft()
print ("Deleting from left - ")
print (DoubleEnded)

输出

当上面的代码执行时,会产生如下结果 −

Appended at right - 
deque(['Mon', 'Tue', 'Wed', 'Thu'])
Appended at right at left is - 
deque(['Sun', 'Mon', 'Tue', 'Wed', 'Thu'])
Deleting from right - 
deque(['Sun', 'Mon', 'Tue', 'Wed'])
Deleting from left - 
deque(['Mon', 'Tue', 'Wed'])