package main import ( "container/list" "fmt" ) func main() { dq := list.New() dq.PushBack(10) dq.PushFront(20) dq.PushBack(30) dq.Remove(dq.Front()) for e := dq.Front(); e != nil; e = e.Next() { fmt.Print(e.Value, " -> ") } fmt.Print("null") }
Remember that PushFront adds to the front and Remove removes the element passed.
Initially, 10 is added at back, then 20 at front, then 30 at back. The dequeue looks like: 20 -> 10 -> 30. Removing the front element (20) leaves 10 -> 30.
package main import ( "container/list" "fmt" ) func main() { dq := list.New() removed := dq.Remove(dq.Front()) fmt.Println(removed) }
Check what dq.Front() returns when the list is empty.
If the list is empty, dq.Front() returns nil. Removing nil returns nil without panic.
package main import ( "container/list" "fmt" ) func main() { dq := list.New() dq.PushBack(1) dq.PushBack(2) dq.PushFront(3) dq.Remove(dq.Back()) dq.Remove(dq.Back()) dq.Remove(dq.Back()) dq.Remove(dq.Back()) for e := dq.Front(); e != nil; e = e.Next() { fmt.Print(e.Value, " -> ") } fmt.Print("null") }
Consider what happens when you remove elements more times than the dequeue has.
Removing elements until the dequeue is empty leaves no elements. Removing from empty returns nil and does nothing. The final print shows just "null".
Think about how linked lists work for insertions and deletions at ends.
Go's container/list is a doubly linked list. Adding or removing at front or back is done in constant time O(1).
package main import ( "container/list" "fmt" ) func main() { dq := list.New() dq.PushBack(5) dq.PushFront(10) dq.PushBack(15) dq.Remove(dq.Front()) dq.PushFront(20) dq.Remove(dq.Back()) dq.PushBack(25) for e := dq.Front(); e != nil; e = e.Next() { fmt.Print(e.Value, " -> ") } fmt.Print("null") }
Track each operation step-by-step to see how the dequeue changes.
Operations step-by-step:
PushBack(5): 5
PushFront(10): 10 -> 5
PushBack(15): 10 -> 5 -> 15
Remove Front (10): 5 -> 15
PushFront(20): 20 -> 5 -> 15
Remove Back (15): 20 -> 5
PushBack(25): 20 -> 5 -> 25
