package main
import (
"fmt"
)
type Deque struct {
items []int
}
func (d *Deque) AddFront(val int) {
d.items = append([]int{val}, d.items...)
}
func (d *Deque) AddBack(val int) {
d.items = append(d.items, val)
}
func (d *Deque) RemoveFront() (int, bool) {
if len(d.items) == 0 {
return 0, false
}
val := d.items[0]
d.items = d.items[1:]
return val, true
}
func (d *Deque) RemoveBack() (int, bool) {
if len(d.items) == 0 {
return 0, false
}
val := d.items[len(d.items)-1]
d.items = d.items[:len(d.items)-1]
return val, true
}
func (d *Deque) String() string {
if len(d.items) == 0 {
return "front -> back"
}
res := "front -> "
for i, v := range d.items {
res += fmt.Sprintf("[%d]", v)
if i != len(d.items)-1 {
res += " -> "
}
}
res += " -> back"
return res
}
func main() {
d := Deque{}
d.AddFront(1) // add 1 at front
fmt.Println(d.String())
d.AddBack(2) // add 2 at back
fmt.Println(d.String())
d.AddFront(3) // add 3 at front
fmt.Println(d.String())
removed, ok := d.RemoveBack() // remove from back
if ok {
fmt.Printf("Removed from back: %d\n", removed)
}
fmt.Println(d.String())
}
d.items = append([]int{val}, d.items...)
insert new value at front by creating new slice with val first
d.items = append(d.items, val)
append new value at back by adding to end of slice
val := d.items[0]
d.items = d.items[1:]
remove front element by slicing off first item
val := d.items[len(d.items)-1]
d.items = d.items[:len(d.items)-1]
remove back element by slicing off last item
front -> [1] -> back
front -> [1] -> [2] -> back
front -> [3] -> [1] -> [2] -> back
Removed from back: 2
front -> [3] -> [1] -> back