Ich habe gelernt Go, und ich machte ein BFS-Puzzle mit ihm. Die Warteschlange Implementierung entschied ich mich auf ist:Warteschlange von Strukturen in Go
//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
}
Ich habe 2 Fragen:
Ist das eine gute Umsetzung? Die Dokumentation zu Warteschlangen ist spärlich, und im Allgemeinen gibt es einige alte Einträge über Vektoren, und eine Liste scheint zu viel Overhead zu haben (nicht dass es für meinen Fall wichtig ist, aber ich versuche es so gut wie möglich zu machen) .
Warum muss der Aufruf eines Objekts (in diesem Fall der Strukturzeiger F * frontier) ein Zeiger sein? Es scheint, wie die Art und Weise die Syntax funktioniert, dass es ein Standard für einen Zeiger sein sollte, nicht explizit (also warum sollten Sie immer keinen Zeiger in diesen Fällen verwenden?)
KREIS VERSION MODIFIED:
//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
}
Mögliche Duplikat [Wie eine Warteschlange in Gehe zu implementieren?] (Http://stackoverflow.com/questions/3042329/how- to-implement-a-queue-in-go) –