Basic Definition
Queue or often we know is a queue data structure where the data we enter will be delivered, in other words the first data will come out first. Usually we often know that Istra FIFO (First in First Out).
According to information that Santekno can, Queue or queue is a collection of data whose additional elements can only be done at one end (called on the back side or rear), and delete or take elements done through another end (called the front or front side).
Queue Implementation
package main
type Queue struct {
items []int
}
func (q *Queue) Enqueue(i int) {
q.items = append(q.items, i)
}
func (q *Queue) Dequeue() int {
if len(q.items) == 0 {
return -1
}
item, items := q.items[0], q.items[1:]
q.items = items
return item
}
func main() {
q := Queue{}
q.Enqueue(1)
q.Enqueue(2)
q.Enqueue(3)
println(q.Dequeue())
println(q.Dequeue())
println(q.Dequeue())
}
Queue Implementation with Channel
package main
type Queue struct {
items chan int
}
func (q *Queue) Enqueue(i int) {
q.items <- i
}
func (q *Queue) Dequeue() int {
return <-q.items
}
func main() {
q := Queue{
items: make(chan int, 16),
}
q.Enqueue(1)
q.Enqueue(2)
q.Enqueue(3)
println(q.Dequeue())
println(q.Dequeue())
println(q.Dequeue())
}
Explanation
If you have seen how to implement the queue, the core of the data structure there are 2 enqueue
operations, namely entering data into the rear elements (rear) and dequeue
which is to retrieve data in the front side elements (front).
Previous post