题目来源:https://leetcode.cn/leetbook/read/queue-stack/kzlb5/
package main
import "fmt"
// 设计循环队列 ,一个长度为N的循环队列
func main() {
a := Constructor(3)
fmt.Println(a.EnQueue(1))
fmt.Println(a.EnQueue(2))
fmt.Println(a.EnQueue(3))
fmt.Println(a.EnQueue(4))
fmt.Println(a.Rear())
fmt.Println(a.IsFull())
fmt.Println(a.DeQueue())
fmt.Println(a.EnQueue(4))
fmt.Println(a.Rear())
}
func Constructor(k int) MyCircularQueue {
return MyCircularQueue{
len: k,
list: make([]int, k),
str: -1,
end: -1,
}
}
type MyCircularQueue struct {
len int
list []int
str, end int
}
func (q *MyCircularQueue) EnQueue(value int) bool {
if q.IsFull() {
return false
}
if q.IsEmpty() {
q.str = 0
}
q.end = (q.end + 1) % q.len
q.list[q.end] = value
return true
}
func (q *MyCircularQueue) DeQueue() bool {
if q.IsEmpty() {
return false
}
if q.str == q.end {
q.str = -1
q.end = -1
return true
}
q.str = (q.str + 1) % q.len
return true
}
func (q *MyCircularQueue) Front() int {
if q.IsEmpty() {
return -1
}
return q.list[q.str]
}
func (q *MyCircularQueue) Rear() int {
if q.IsEmpty() {
return -1
}
return q.list[q.end]
}
func (q *MyCircularQueue) IsEmpty() bool {
if q.end == -1 && q.str == -1 {
return true
}
return false
}
func (q *MyCircularQueue) IsFull() bool {
return (q.end+1)%q.len == q.str
}
我有N台文件服务器,需要实现负载均衡
// 简单的轮训算法
current = (current + 1) % n