题解 | 【模板】队列操作
【模板】队列操作
https://www.nowcoder.com/practice/1137c8f6ffac4d5d94cc1b0cb08723f9
import sys
input = sys.stdin.read
data = input().split()
n = int(data[0])
queue = []
index = 1
output_lines = []
for _ in range(n):
op = data[index]; index += 1
if op == '1':
x = int(data[index]); index += 1
queue.append(x)
elif op == '2':
if queue:
queue.pop(0) # 使用 list.pop(0) 删除第一个元素是 O(n) 操作,效率低!
# 可以使用双端队列
else:
output_lines.append('ERR_CANNOT_POP')
elif op == '3':
if queue:
output_lines.append(queue[0])
else:
output_lines.append('ERR_CANNOT_QUERY')
elif op == '4':
output_lines.append(len(queue))
print('\n'.join(map(str,output_lines))) # 使用join前确保每个元素都是 str
查看2道真题和解析