Golang is a very popular programming language. One of its advantages is that it can implement many data structures and algorithms with simple syntax. As a common data structure, queue also has a very simple and easy-to-use implementation in Golang.
So, how to use Golang to implement a queue? Below we will introduce an array-based queue implementation.
First, we need to define a structure to represent the queue:
type Queue struct { queue []interface{} front int rear int }
Among them, queue
is an array used to store the elements in the queue, front
and rear
represent the indexes of the head and tail of the queue respectively.
Next, we can define several basic operation methods of the queue:
func (q *Queue) Enqueue(item interface{}) { q.queue = append(q.queue, item) q.rear++ }
In this method, we pass# The ##append method adds the element to the end of the queue and increments the value of
rear by 1.
func (q *Queue) Dequeue() interface{} { if q.front == q.rear { return nil } item := q.queue[q.front] q.front++ return item }
front and
rear Whether they are equal. If it is empty, return
nil directly, otherwise take out the front element and add 1 to the value of
front.
func (q *Queue) Peek() interface{} { if q.front == q.rear { return nil } return q.queue[q.front] }
func (q *Queue) IsEmpty() bool { return q.front == q.rear }
func (q *Queue) Size() int { return q.rear - q.front }
rear and
front Just the difference.
type Queue struct { queue []interface{} front int rear int } func (q *Queue) Enqueue(item interface{}) { q.queue = append(q.queue, item) q.rear++ } func (q *Queue) Dequeue() interface{} { if q.front == q.rear { return nil } item := q.queue[q.front] q.front++ return item } func (q *Queue) Peek() interface{} { if q.front == q.rear { return nil } return q.queue[q.front] } func (q *Queue) IsEmpty() bool { return q.front == q.rear } func (q *Queue) Size() int { return q.rear - q.front } func main() { q := &Queue{} q.Enqueue(1) q.Enqueue(2) q.Enqueue(3) fmt.Println(q.Size()) fmt.Println(q.Peek()) fmt.Println(q.Dequeue()) fmt.Println(q.IsEmpty()) }
The above is the detailed content of How to implement a queue using Golang. For more information, please follow other related articles on the PHP Chinese website!