我一直在学习Go,我用它做了一个BFS游戏。我决定的队列实现是:
//define the queue for our BFS algo as frontier.
type frontier struct {
queue []*graphNode
}
func (F *frontier) buildFrontier() {
F.queue = make([]*graphNode, 0, 1000)
}
func (F *frontier) pop() (g *graphNode) {
if F.isEmpty() {
panic("pop on empty queue!")
}
temp := F.queue[0]
F.queue = F.queue[1:]
return temp
}
func (F *frontier) push(g *graphNode) {
F.queue = append(F.queue, g)
}
func (F *frontier) isEmpty() bool {
return len(F.queue) == 0
}我有两个问题:
修改后的循环版本:
//define the queue for our BFS algo as frontier.
type frontier struct {
queue []*graphNode
size, head, capacity int
}
func (F *frontier) buildFrontier() {
F.capacity = 1
F.queue = make([]*graphNode, F.capacity)
F.size = 0
F.head = 0
}
func (F *frontier) pop() (g *graphNode) {
if F.isEmpty() {
panic("pop on empty queue!")
}
F.size = (F.size - 1)
temp := F.queue[F.head]
F.head = (F.head + 1) % F.capacity
return temp
}
func (F *frontier) push(g *graphNode) {
if F.isFull() {
newSlice := make([]*graphNode, F.capacity*2)
copy(newSlice, F.queue)
F.queue = newSlice
F.capacity *= 2
}
F.queue[(F.head+F.size)%F.capacity] = g
F.size = (F.size + 1)
}
func (F *frontier) isEmpty() bool {
return F.size == 0
}
func (F *frontier) isFull() bool {
return F.size == F.capacity
}发布于 2017-04-13 15:07:43
queue是一个容量为1000的片。这意味着基础数组可以容纳1000个元素。每次调用pop时,都会将队列的开头--一个元素进一步向下移动--从而使容量减少1。最终,当调用push时,容量将不足以容纳一个新元素,即使队列中可能没有很多(或任何)元素。这将导致在调用append时分配一个新数组。无论push和pop调用的模式是什么,数组都将被反复重新分配,即使它从未包含接近1000个元素的任何位置。我建议为此使用一个链接列表,无论是在list包中还是在您自己的设计中。https://stackoverflow.com/questions/43395303
复制相似问题