github.com/gopherd/gonum@v0.0.4/graph/internal/linear/linear.go (about) 1 // Copyright ©2015 The Gonum Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package linear 6 7 import ( 8 "github.com/gopherd/gonum/graph" 9 ) 10 11 // NodeStack implements a LIFO stack of graph.Node. 12 type NodeStack []graph.Node 13 14 // Len returns the number of graph.Nodes on the stack. 15 func (s *NodeStack) Len() int { return len(*s) } 16 17 // Pop returns the last graph.Node on the stack and removes it 18 // from the stack. 19 func (s *NodeStack) Pop() graph.Node { 20 v := *s 21 v, n := v[:len(v)-1], v[len(v)-1] 22 *s = v 23 return n 24 } 25 26 // Push adds the node n to the stack at the last position. 27 func (s *NodeStack) Push(n graph.Node) { *s = append(*s, n) } 28 29 // NodeQueue implements a FIFO queue. 30 type NodeQueue struct { 31 head int 32 data []graph.Node 33 } 34 35 // Len returns the number of graph.Nodes in the queue. 36 func (q *NodeQueue) Len() int { return len(q.data) - q.head } 37 38 // Enqueue adds the node n to the back of the queue. 39 func (q *NodeQueue) Enqueue(n graph.Node) { 40 if len(q.data) == cap(q.data) && q.head > 0 { 41 l := q.Len() 42 copy(q.data, q.data[q.head:]) 43 q.head = 0 44 q.data = append(q.data[:l], n) 45 } else { 46 q.data = append(q.data, n) 47 } 48 } 49 50 // Dequeue returns the graph.Node at the front of the queue and 51 // removes it from the queue. 52 func (q *NodeQueue) Dequeue() graph.Node { 53 if q.Len() == 0 { 54 panic("queue: empty queue") 55 } 56 57 var n graph.Node 58 n, q.data[q.head] = q.data[q.head], nil 59 q.head++ 60 61 if q.Len() == 0 { 62 q.head = 0 63 q.data = q.data[:0] 64 } 65 66 return n 67 } 68 69 // Reset clears the queue for reuse. 70 func (q *NodeQueue) Reset() { 71 q.head = 0 72 q.data = q.data[:0] 73 }