hello-algo/codes/python/chapter_stack_and_queue/deque.py

43 lines
1.1 KiB
Python
Raw Normal View History

"""
File: deque.py
2022-11-30 12:15:50 +08:00
Created Time: 2022-11-29
Author: Peng Chen (pengchzn@gmail.com)
"""
from collections import deque
"""Driver Code"""
2022-11-30 12:15:50 +08:00
if __name__ == "__main__":
2023-04-09 05:05:35 +08:00
# 初始化双向队列
deq: deque[int] = deque()
2022-11-30 12:15:50 +08:00
2023-04-09 05:05:35 +08:00
# 元素入队
deq.append(2) # 添加至队尾
deq.append(5)
deq.append(4)
deq.appendleft(3) # 添加至队首
deq.appendleft(1)
print("双向队列 deque =", deq)
2022-11-30 12:15:50 +08:00
2023-04-09 05:05:35 +08:00
# 访问元素
front: int = deq[0] # 队首元素
print("队首元素 front =", front)
rear: int = deq[-1] # 队尾元素
print("队尾元素 rear =", rear)
2022-11-30 12:15:50 +08:00
2023-04-09 05:05:35 +08:00
# 元素出队
pop_front: int = deq.popleft() # 队首元素出队
print("队首出队元素 pop_front =", pop_front)
print("队首出队后 deque =", deq)
2023-04-09 05:05:35 +08:00
pop_rear: int = deq.pop() # 队尾元素出队
print("队尾出队元素 pop_rear =", pop_rear)
print("队尾出队后 deque =", deq)
2022-11-30 12:15:50 +08:00
2023-04-09 05:05:35 +08:00
# 获取双向队列的长度
size: int = len(deq)
print("双向队列长度 size =", size)
2022-11-30 12:15:50 +08:00
2023-04-09 05:05:35 +08:00
# 判断双向队列是否为空
is_empty: bool = len(deq) == 0
print("双向队列是否为空 =", is_empty)