Deque

A deque, or a double-ended queue, is a container that can be expanded. These expansions can occur in the front or the back of the container. Deques are often used when the top or the back of a queue needs to be referenced frequently. The following code block is a simple implementation of a deque:

package main

import (
"fmt"

"gopkg.in/karalabe/cookiejar.v1/collections/deque"
)

func main() {
d := deque.New()
elements := []string{"foo", "bar", "baz"}
for i := range elements {
d.PushLeft(elements[i])
}
fmt.Println(d.PopLeft()) // queue => ["foo", "bar"]
fmt.Println(d.PopRight()) // queue => ["bar"]
fmt.Println(d.PopLeft()) // queue => empty
}

The deque package takes a slice of elements and pushes them onto the queue with the PushLeft function. Next, we can pop elements off of the left and the right of the deque, until our queue is empty. We can see the execution of our deque logic in the following screenshot:

Our results show the output of the manipulation of the deque and how we can pull things from either end of the queue. Being able to pull things from either end of the queue is advantageous in data manipulation, and this is why a deque is a popular data structure choice.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.66.156