Stack:後進先出 (LIFO)
Queue:先進先出 (FIFO)
List
實作# Stack
stack = ["Red", "Yellow", "White"]
stack.append("Black")
stack.pop() # stack = ['Red', 'Yellow', 'White']
# Queue
queue = ["Red", "Yellow", "White"]
queue.append("Black")
queue.pop(0) # queue = ['Yellow', 'White', 'Black']
Deque
Deque 是 “double-ended queue”的縮寫,內部是由 doubly-linked list 來實現.
因為它每個節點儲存了至少兩個指標變數,所以用Deque來實作 Stack 跟 Queue 會比用 List 更耗費記憶體空間.關於 Deque 跟 List 的詳細比較可以參考這篇
from collections import deque
# Stack
stack = deque(["Red", "Yellow", "White"])
stack.append("Black")
top = stack.pop() # stack = deque(['Red', 'Yellow', 'White'])
# Queue
queue = deque(["Red", "Yellow", "White"])
queue.append("Black")
first = queue.popleft() # queue = deque(['Yellow', 'White', 'Black'])
Go 沒有內建的Deque模組來協助實作 Stack 跟 Queue.
所以我們只能用第三方套件或內建的 Slice 來手動實現.
stack
package main
import (
"errors"
"fmt"
)
type stack []int
func (s *stack) IsEmpty() bool {
return len(*s) == 0
}
func (s *stack) Push(val int) {
*s = append(*s, val)
}
func (s *stack) Pop() {
if s.IsEmpty() {
errors.New("Stack is empty")
}
*s = (*s)[:len(*s)-1]
}
func main() {
myStack := stack{}
myStack.Push(1)
myStack.Push(2)
fmt.Println(myStack)
myStack.Pop()
fmt.Println(myStack)
myStack.Pop()
myStack.Pop()
}
queue
package main
import (
"errors"
"fmt"
)
type queue []int
func (s *queue) IsEmpty() bool {
return len(*s) == 0
}
func (s *queue) Enqueue(val int) {
*s = append(*s, val)
}
func (s *queue) Dequeue() {
if s.IsEmpty() {
errors.New("Queue is empty")
}
*s = (*s)[1:len(*s)]
}
func main() {
myQueue := queue{}
myQueue.Enqueue(1)
myQueue.Enqueue(2)
fmt.Println(myQueue)
myQueue.Dequeue()
fmt.Println(myQueue)
myQueue.Dequeue()
myQueue.Dequeue()
}