2022-12-23 00:44:40 +08:00
|
|
|
"""
|
2022-12-06 01:00:21 +08:00
|
|
|
File: queue.py
|
2022-11-30 12:15:50 +08:00
|
|
|
Created Time: 2022-11-29
|
|
|
|
Author: Peng Chen (pengchzn@gmail.com)
|
2022-12-23 00:44:40 +08:00
|
|
|
"""
|
2022-11-25 02:04:38 +08:00
|
|
|
|
2023-03-23 18:51:56 +08:00
|
|
|
from collections import deque
|
2022-11-30 12:15:50 +08:00
|
|
|
|
2023-04-09 05:30:02 +08:00
|
|
|
"""Driver Code"""
|
2023-03-23 18:51:56 +08:00
|
|
|
if __name__ == "__main__":
|
2023-04-09 05:05:35 +08:00
|
|
|
# 初始化队列
|
2023-03-12 18:49:52 +08:00
|
|
|
# 在 Python 中,我们一般将双向队列类 deque 看作队列使用
|
|
|
|
# 虽然 queue.Queue() 是纯正的队列类,但不太好用
|
2023-03-23 18:51:56 +08:00
|
|
|
que: deque[int] = deque()
|
2022-11-30 12:15:50 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
# 元素入队
|
2022-12-02 00:09:34 +08:00
|
|
|
que.append(1)
|
|
|
|
que.append(3)
|
|
|
|
que.append(2)
|
|
|
|
que.append(5)
|
|
|
|
que.append(4)
|
|
|
|
print("队列 que =", que)
|
2022-11-30 12:15:50 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
# 访问队首元素
|
2023-03-12 18:49:52 +08:00
|
|
|
front: int = que[0]
|
|
|
|
print("队首元素 front =", front)
|
2022-11-30 12:15:50 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
# 元素出队
|
2023-03-12 18:49:52 +08:00
|
|
|
pop: int = que.popleft()
|
2022-12-02 00:09:34 +08:00
|
|
|
print("出队元素 pop =", pop)
|
|
|
|
print("出队后 que =", que)
|
2022-11-30 12:15:50 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
# 获取队列的长度
|
2023-03-12 18:49:52 +08:00
|
|
|
size: int = len(que)
|
2022-12-02 00:09:34 +08:00
|
|
|
print("队列长度 size =", size)
|
2022-11-30 12:15:50 +08:00
|
|
|
|
2023-04-09 05:05:35 +08:00
|
|
|
# 判断队列是否为空
|
2023-03-12 18:49:52 +08:00
|
|
|
is_empty: bool = len(que) == 0
|
2022-12-02 00:09:34 +08:00
|
|
|
print("队列是否为空 =", is_empty)
|