- Python 資料結構與演算法教程
- Python - 資料結構 首頁
- Python - 資料結構 簡介
- Python - 資料結構 環境
- Python - 陣列
- Python - 列表
- Python - 元組
- Python - 字典
- Python - 二維陣列
- Python - 矩陣
- Python - 集合
- Python - 對映
- Python - 連結串列
- Python - 棧
- Python - 佇列
- Python - 雙端佇列
- Python - 高階連結串列
- Python - 雜湊表
- Python - 二叉樹
- Python - 搜尋樹
- Python - 堆
- Python - 圖
- Python - 演算法設計
- Python - 分治法
- Python - 遞迴
- Python - 回溯法
- Python - 排序演算法
- Python - 搜尋演算法
- Python - 圖演算法
- Python - 演算法分析
- Python - 大O表示法
- Python - 演算法分類
- Python - 均攤分析
- Python - 演算法論證
- Python 資料結構與演算法有用資源
- Python - 快速指南
- Python - 有用資源
- Python - 討論
Python - 佇列
我們在日常生活中對佇列很熟悉,就像我們等待服務一樣。佇列資料結構也意味著相同的資料元素排列在佇列中。佇列的獨特性在於專案新增和刪除的方式。專案允許在一端新增,但從另一端移除。所以它是一種先進先出(FIFO)的方法。
可以使用 Python 列表實現佇列,其中我們可以使用 insert() 和 pop() 方法來新增和刪除元素。由於資料元素總是新增到佇列的末尾,因此沒有中間插入。
新增元素
在下面的示例中,我們建立了一個佇列類,其中我們實現了先進先出方法。我們使用內建的 insert 方法新增資料元素。
示例
class Queue:
def __init__(self):
self.queue = list()
def addtoq(self,dataval):
# Insert method to add element
if dataval not in self.queue:
self.queue.insert(0,dataval)
return True
return False
def size(self):
return len(self.queue)
TheQueue = Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.size())
輸出
執行上述程式碼後,將產生以下結果:
3
刪除元素
在下面的示例中,我們建立了一個佇列類,我們插入資料,然後使用內建的 pop 方法刪除資料。
示例
class Queue:
def __init__(self):
self.queue = list()
def addtoq(self,dataval):
# Insert method to add element
if dataval not in self.queue:
self.queue.insert(0,dataval)
return True
return False
# Pop method to remove element
def removefromq(self):
if len(self.queue)>0:
return self.queue.pop()
return ("No elements in Queue!")
TheQueue = Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.removefromq())
print(TheQueue.removefromq())
輸出
執行上述程式碼後,將產生以下結果:
Mon Tue
廣告