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

48 lines
1.3 KiB
Python
Raw Normal View History

'''
File: deque.py
2022-11-30 04:15:50 +00:00
Created Time: 2022-11-29
Author: Peng Chen (pengchzn@gmail.com)
'''
2022-11-30 04:15:50 +00:00
import os.path as osp
import sys
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from include import *
2022-11-30 04:15:50 +00:00
from collections import deque
if __name__ == "__main__":
""" 初始化双向队列 """
duque = deque()
""" 元素入队 """
duque.append(2) # 添加至队尾
duque.append(5)
duque.append(4)
duque.appendleft(3) # 添加至队首
duque.appendleft(1)
print("双向队列 duque = ", duque)
""" 访问队首元素 """
peekFirst = duque[0] # 队首元素
print("队首元素 peekFirst = ", peekFirst)
peekLast = duque[-1] # 队尾元素
print("队尾元素 peekLast = ", peekLast)
""" 元素出队 """
popFirst = duque.pop() # 队首元素出队
print("队首出队元素 popFirst= ", popFirst)
print("队首出队后 duque = ", duque)
popLast = duque.popleft() # 队尾元素出队
print("队尾出队元素 popLast= ", popLast)
print("队尾出队后 duque = ", duque)
2022-11-30 22:53:08 +00:00
""" 获取双向队列的长度 """
2022-11-30 04:15:50 +00:00
size = len(duque)
2022-11-30 22:53:08 +00:00
print("双向队列长度 size = ", size)
2022-11-30 04:15:50 +00:00
2022-11-30 22:53:08 +00:00
""" 判断双向队列是否为空 """
2022-11-30 04:15:50 +00:00
is_empty = len(duque) == 0
2022-11-30 22:53:08 +00:00
print("双向队列是否为空 = ", is_empty)