Imagine you have multiple tasks to do in order. Which data structure helps you keep the order of tasks exactly as they arrive?
Think about waiting in line at a store. Who gets served first?
A queue processes items in the order they arrive, which is perfect for scheduling tasks that must happen in sequence. A stack reverses the order, which is not suitable here.
Consider a queue where you add numbers 1, 2, 3, then remove one item. What is the state of the queue?
package main import ( "container/list" "fmt" ) func main() { queue := list.New() queue.PushBack(1) queue.PushBack(2) queue.PushBack(3) queue.Remove(queue.Front()) for e := queue.Front(); e != nil; e = e.Next() { fmt.Print(e.Value, " -> ") } fmt.Print("null") }
Removing from the front removes the first item added.
After adding 1, 2, 3, the queue is 1 -> 2 -> 3. Removing the front removes 1, leaving 2 -> 3.
What error will this Go code cause when trying to dequeue from an empty queue?
package main import ( "container/list" "fmt" ) func main() { queue := list.New() front := queue.Front() queue.Remove(front) fmt.Println("Removed front element") }
What happens if you try to remove an element from an empty list?
Calling Remove on a nil element causes a runtime panic because there is no element to remove.
Choose the scenario where a queue data structure is the best fit.
Think about tasks that must be handled in the exact order they arrive.
Printing jobs must be handled in the order they arrive, so a queue (FIFO) is ideal. Undo uses a stack (LIFO).
Trace the queue state after these operations: enqueue 10, enqueue 20, dequeue, enqueue 30, dequeue, enqueue 40.
package main import ( "container/list" "fmt" ) func main() { queue := list.New() queue.PushBack(10) // enqueue 10 queue.PushBack(20) // enqueue 20 queue.Remove(queue.Front()) // dequeue (removes 10) queue.PushBack(30) // enqueue 30 queue.Remove(queue.Front()) // dequeue (removes 20) queue.PushBack(40) // enqueue 40 for e := queue.Front(); e != nil; e = e.Next() { fmt.Print(e.Value, " -> ") } fmt.Print("null") }
Remove items from the front in the order they were added.
After removing 10 and 20, the queue has 30 and 40 in order.
