# 用go实现常用算法与数据结构——队列(queue)

## 实现

https://github.com/AceDarkknight/AlgorithmAndDataStructure/tree/master/queue

``````type Queue interface {
// 获取当前链表长度。
Length() int
// 获取当前链表容量。
Capacity() int
// 获取当前链表头结点。
Front() *Node
// 获取当前链表尾结点。
Rear() *Node
// 入列。
Enqueue(value interface{}) bool
// 出列。
Dequeue() interface{}
}``````

### 链表实现的队列

``````// normalQueue.go
func (q *NormalQueue) Enqueue(value interface{}) bool {
if q.length == q.capacity || value == nil {
return false
}

node := &Node{
value: value,
}

if q.length == 0 {
q.front.next = node
}

node.previous = q.rear.previous
node.next = q.rear
q.rear.previous.next = node
q.rear.previous = node
q.length++

return true
}``````

``````// normalQueue.go
func (q *NormalQueue) Dequeue() interface{} {
if q.length == 0 {
return nil
}

result := q.front.next
q.front.next = result.next
result.next = nil
result.previous = nil
q.length--

return result.value
}``````

### 无重复元素的队列。

``````// uniqueQueue.go
func (q *UniqueQueue) Enqueue(value interface{}) bool {
if q.length == q.capacity || value == nil {
return false
}

node := &Node{
value: value,
}

// Ignore uncomparable type.
if kind := reflect.TypeOf(value).Kind(); kind == reflect.Map || kind == reflect.Slice || kind == reflect.Func {
return false
}

if v, ok := q.nodeMap[value]; ok || v {
return false
}

if q.length == 0 {
q.front.next = node
}

node.previous = q.rear.previous
node.next = q.rear
q.rear.previous.next = node
q.rear.previous = node

q.nodeMap[value] = true

q.length++

return true
}``````

``````// uniqueQueue.go
func (q *UniqueQueue) Dequeue() interface{} {
if q.length == 0 {
return nil
}

result := q.front.next

delete(q.nodeMap, result.value)

q.front.next = result.next
result.next = nil
result.previous = nil

q.length--

return result.value
}``````

### 循环队列

``````// cyclicQueue.go
func (q *CyclicQueue) Enqueue(value interface{}) bool {
if q.length == q.capacity || value == nil {
return false
}

node := &Node{
value: value,
}

index := (q.rear + 1) % cap(q.nodes)
q.nodes[index] = node
q.rear = index
q.length++

if q.length == 1 {
q.front = index
}

return true
}``````

``````// cyclicQueue.go
func (q *CyclicQueue) Dequeue() interface{} {
if q.length == 0 {
return nil
}

result := q.nodes[q.front].value
q.nodes[q.front] = nil
index := (q.front + 1) % cap(q.nodes)
q.front = index
q.length--

return result
}``````

## Reference

https://www.geeksforgeeks.org/queue-set-1introduction-and-array-implementation/

原文作者：DilonWu
原文地址: https://www.cnblogs.com/DilonWu/p/8972288.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。