Implement stacks, queues and deques
Implement stacks, queues and deques
A stack removes the newest item first (LIFO); a queue removes the oldest first (FIFO). A deque permits insertion and removal at both ends. Choose by access order: undo history uses a stack, waiting jobs use a queue. A slice supports convenient stack operations at its end.
package main
import ( "fmt")
func pop(s []int) ([]int, int, bool) { if len(s) == 0 { return s, 0, false } i := len(s) - 1 v := s[i] return s[:i], v, true}func main() { s := []int{1, 2} s = append(s, 3) s, v, ok := pop(s) fmt.Println(v, ok, s) _, _, ok = pop(nil) fmt.Println(ok)}The caller must store the returned slice: shortening the local descriptor does not shorten the caller’s descriptor. A bool distinguishes empty from a valid zero. Pop is O(1); append may occasionally copy elements when capacity is exhausted. For references, clear removed slots before shortening when retaining the backing array.
Expected output:
3 true [1 2]falseA deque using container/list
package main
import ( "container/list" "fmt")
func main() { var q list.List q.PushBack("B") q.PushFront("A") q.PushBack("C") fmt.Println(q.Remove(q.Front()), q.Remove(q.Back()), q.Len())}container/list supplies a doubly linked list; PushFront and PushBack insert at the two ends, Front and Back return element pointers or nil. Remove needs a valid element from that list. Check emptiness first. A FIFO queue only pushes back and removes front. List entries use any; a typed slice can be simpler and more compact.
Expected output:
A C 1Try it locally
Use a list as a FIFO queue. Enqueue 0, 7, 9; remove the first two, printing each, then print the remaining length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Data structures 01: Implement stacks, queues and deques
Check the lesson objective before moving on.
Which order does a stack use?
What should you check before removing Front()?