linear.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. // Package linear provides common linear data structures.
  5. package linear
  6. import (
  7. "k8s.io/kubernetes/third_party/forked/gonum/graph"
  8. )
  9. // NodeStack implements a LIFO stack of graph.Node.
  10. type NodeStack []graph.Node
  11. // Len returns the number of graph.Nodes on the stack.
  12. func (s *NodeStack) Len() int { return len(*s) }
  13. // Pop returns the last graph.Node on the stack and removes it
  14. // from the stack.
  15. func (s *NodeStack) Pop() graph.Node {
  16. v := *s
  17. v, n := v[:len(v)-1], v[len(v)-1]
  18. *s = v
  19. return n
  20. }
  21. // Push adds the node n to the stack at the last position.
  22. func (s *NodeStack) Push(n graph.Node) { *s = append(*s, n) }
  23. // NodeQueue implements a FIFO queue.
  24. type NodeQueue struct {
  25. head int
  26. data []graph.Node
  27. }
  28. // Len returns the number of graph.Nodes in the queue.
  29. func (q *NodeQueue) Len() int { return len(q.data) - q.head }
  30. // Enqueue adds the node n to the back of the queue.
  31. func (q *NodeQueue) Enqueue(n graph.Node) {
  32. if len(q.data) == cap(q.data) && q.head > 0 {
  33. l := q.Len()
  34. copy(q.data, q.data[q.head:])
  35. q.head = 0
  36. q.data = append(q.data[:l], n)
  37. } else {
  38. q.data = append(q.data, n)
  39. }
  40. }
  41. // Dequeue returns the graph.Node at the front of the queue and
  42. // removes it from the queue.
  43. func (q *NodeQueue) Dequeue() graph.Node {
  44. if q.Len() == 0 {
  45. panic("queue: empty queue")
  46. }
  47. var n graph.Node
  48. n, q.data[q.head] = q.data[q.head], nil
  49. q.head++
  50. if q.Len() == 0 {
  51. q.head = 0
  52. q.data = q.data[:0]
  53. }
  54. return n
  55. }
  56. // Reset clears the queue for reuse.
  57. func (q *NodeQueue) Reset() {
  58. q.head = 0
  59. q.data = q.data[:0]
  60. }