队列和堆栈

把列表当堆栈使用,堆栈作为一个特定的数据结构,它的特点是后进先出,用append()方法可以把一个元素添加到堆栈顶,用不指定索引的pop()方法可以把一个元素从堆栈顶释放出来

stack=[3,4,5]
stack.append(6)
stack.append(7)
print(stack)
print(stack.pop())
print(stack)
print(stack.pop())
print(stack.pop())
print(stack)

#[3, 4, 5, 6, 7]
#7
#[3, 4, 5, 6]
#6
#5
#[3, 4]

把列表当队列使用,队列是先进先出

方法一

from collections import deque
queue=deque(['eric','john','michael'])
queue.append('terry')
queue.append('graham')
print(queue.popleft())
print(queue.popleft())
print(queue)

#eric
#john
#deque(['michael', 'terry', 'graham'])

方法二

queue=[3,4,5]
queue.append(6)
queue.append(7)
print(queue)
print(queue.pop(0))
print(queue)
print(queue.pop(0))
print(queue.pop(0))
print(queue)


#[3, 4, 5, 6, 7]
#3
#[4, 5, 6, 7]
#4
#5
#[6, 7]
原文地址:https://www.cnblogs.com/z-x-y/p/9998686.html