Python Deque

双端队列(deque)具有从任一端添加和删除元素的功能。Deque模块是集合库的一部分。它具有添加和删除可以直接用参数调用的元素的方法。在下面的程序中,我们导入集合模块并声明一个双端队列。不需要任何类,我们直接使用内置的实现这些方法。

import collections
# Create a deque
DoubleEnded = collections.deque(["Mon","Tue","Wed"])
print (DoubleEnded)

# Append to the right
print("Adding to the right: ")
DoubleEnded.append("Thu")
print (DoubleEnded)

# append to the left
print("Adding to the left: ")
DoubleEnded.appendleft("Sun")
print (DoubleEnded)

# Remove from the right
print("Removing from the right: ")
DoubleEnded.pop()
print (DoubleEnded)

# Remove from the left
print("Removing from the left: ")
DoubleEnded.popleft()
print (DoubleEnded)

# Reverse the dequeue
print("Reversing the deque: ")
DoubleEnded.reverse()
print (DoubleEnded)

当上面的代码被执行时,它会产生以下结果:

deque(['Mon', 'Tue', 'Wed'])
Adding to the right:
deque(['Mon', 'Tue', 'Wed', 'Thu'])
Adding to the left:
deque(['Sun', 'Mon', 'Tue', 'Wed', 'Thu'])
Removing from the right:
deque(['Sun', 'Mon', 'Tue', 'Wed'])
Removing from the left:
deque(['Mon', 'Tue', 'Wed'])
Reversing the deque:
deque(['Wed', 'Tue', 'Mon'])

在前面的章节中我们已经看到了链接列表,但它只能在前面进行介绍。在本章中,我们看到另一种链接列表,其中可以前进和后退。这样一个链表被称为双链表。以下是双向链表的特点。双链表包含称为第一个和最后一个的链接元素。每个链接都 ...