堆疊Stack與佇列Queue
堆疊Stack
先入後出(FILO, First-in-Last-out)
-
推入 push():將資料放入堆疊頂端,堆疊頂端移到新放入的資料。
-
彈出 pop():將堆疊頂端資料移除,堆疊頂端移到移除後的下一筆資料。
-
peek(): 查出堆疊最上方的元素
-
size(): 查出堆疊共有幾個元素
-
isEmpty(): 是否堆疊內無元素
佇列Queue
先進先出 (First In First Out, FIFO)
可以使用push( )與shift( )來實現。
程式碼範例
Stack 實作
class Stack {
constructor() {
this.items = [];
}
push(item) { this.items.push(item); }
pop() { return this.items.pop(); }
peek() { return this.items[this.items.length - 1]; }
size() { return this.items.length; }
isEmpty() { return this.items.length === 0; }
}
Queue 實作
class Queue {
constructor() {
this.items = [];
}
enqueue(item) { this.items.push(item); }
dequeue() { return this.items.shift(); }
front() { return this.items[0]; }
size() { return this.items.length; }
isEmpty() { return this.items.length === 0; }
}
常見應用
| 資料結構 | 應用場景 |
|---|---|
| Stack | 程式呼叫堆疊、括號配對、「上一步」功能、DFS |
| Queue | BFS、任務排程、訊息佇列、印表機佇列 |