Circular queue is a commonly used data structure, which is characterized by its ability to recycle array space and effectively implement queue operations. In Go language, we can implement a circular queue through an array and two pointers. This article will delve into the implementation of circular queues in the Go language and provide specific code examples.
The implementation principle of circular queue is mainly to use the circular use of arrays, and to mark the head and tail of the queue through two pointers front and rear. When the rear pointer reaches the end of the array, it can be pointed to the beginning of the array again through the modulo operation to achieve recycling of the queue.
Define circular queue structure
type CircularQueue struct { capacity int front int rear int data []interface{} }
Initialize circular queue
func NewCircularQueue(capacity int) *CircularQueue { return &CircularQueue{ capacity: capacity, front: 0, rear: 0, data: make([]interface{}, capacity), } }
Entry operation
func (cq *CircularQueue) Enqueue(val interface{}) bool { if (cq.rear+1)%cq.capacity == cq.front { return false // 队列已满 } cq.data[cq.rear] = val cq.rear = (cq.rear + 1) % cq.capacity return true }
Dequeue operation
func (cq *CircularQueue) Dequeue() interface{} { if cq.front == cq.rear { return nil // 队列为空 } val := cq.data[cq.front] cq.front = (cq.front + 1) % cq.capacity return val }
package main import "fmt" type CircularQueue struct { capacity int front int rear int data []interface{} } func NewCircularQueue(capacity int) *CircularQueue { return &CircularQueue{ capacity: capacity, front: 0, rear: 0, data: make([]interface{}, capacity), } } func (cq *CircularQueue) Enqueue(val interface{}) bool { if (cq.rear+1)%cq.capacity == cq.front { return false } cq.data[cq.rear] = val cq.rear = (cq.rear + 1) % cq.capacity return true } func (cq *CircularQueue) Dequeue() interface{} { if cq.front == cq.rear { return nil } val := cq.data[cq.front] cq.front = (cq.front + 1) % cq.capacity return val } func main() { cq := NewCircularQueue(5) cq.Enqueue(1) cq.Enqueue(2) cq.Enqueue(3) fmt.Println(cq.Dequeue()) fmt.Println(cq.Dequeue()) fmt.Println(cq.Dequeue()) }
Through the above sample code, we have implemented a simple circular queue and implemented the enqueue and dequeue operations. This implementation based on arrays and pointers effectively utilizes fixed-size arrays and implements the basic functions of circular queues.
Summary: Through the introduction of this article, readers can have a deeper understanding of the implementation of circular queues in Go language, and deepen their understanding of circular queues through code examples. Hope this article is helpful to readers.
The above is the detailed content of Learn more about the implementation of circular queues in Go language. For more information, please follow other related articles on the PHP Chinese website!