mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-07 23:04:55 +08:00
Add python code of chapter queue to docs.
This commit is contained in:
@ -1,5 +1,5 @@
|
||||
'''
|
||||
File: queue.py
|
||||
File: que.py
|
||||
Created Time: 2022-11-29
|
||||
Author: Peng Chen (pengchzn@gmail.com)
|
||||
'''
|
||||
@ -10,33 +10,35 @@ import sys
|
||||
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
||||
from include import *
|
||||
|
||||
import queue
|
||||
|
||||
if __name__ == "__main__":
|
||||
""" Driver Code """
|
||||
if __name__ == "__main__":
|
||||
""" 初始化队列 """
|
||||
queue = queue.Queue()
|
||||
# 在 Python 中,我们一般将双向队列类 deque 看左队列使用
|
||||
# 虽然 queue.Queue() 是纯正的队列类,但不太好用,因此不建议
|
||||
que = collections.deque()
|
||||
|
||||
""" 元素入队 """
|
||||
queue.put(1)
|
||||
queue.put(3)
|
||||
queue.put(2)
|
||||
queue.put(5)
|
||||
queue.put(4)
|
||||
print("队列 queue = ", queue.queue)
|
||||
que.append(1)
|
||||
que.append(3)
|
||||
que.append(2)
|
||||
que.append(5)
|
||||
que.append(4)
|
||||
print("队列 que =", que)
|
||||
|
||||
""" 访问队首元素 """
|
||||
peek = queue.queue[0]
|
||||
print("队首元素 peek = ", peek)
|
||||
front = que[0];
|
||||
print("队首元素 front =", front);
|
||||
|
||||
""" 元素出队 """
|
||||
get = queue.get()
|
||||
print("出队元素 get = ", get)
|
||||
print("出队后 queue = ", queue.queue)
|
||||
pop = que.popleft()
|
||||
print("出队元素 pop =", pop)
|
||||
print("出队后 que =", que)
|
||||
|
||||
""" 获取队列的长度 """
|
||||
size = queue.qsize()
|
||||
print("队列长度 size = ", size)
|
||||
size = len(que)
|
||||
print("队列长度 size =", size)
|
||||
|
||||
""" 判断队列是否为空 """
|
||||
is_empty = queue.empty()
|
||||
print("队列是否为空 = ", is_empty)
|
||||
is_empty = len(que) == 0
|
||||
print("队列是否为空 =", is_empty)
|
||||
|
Reference in New Issue
Block a user