Last active
December 18, 2015 09:29
-
-
Save naveensrinivasan/5761654 to your computer and use it in GitHub Desktop.
A simple Queue in go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Any interface{} | |
// Queue is a basic FIFO Queue | |
type Queue struct { | |
nodes []Any | |
size int | |
head int | |
tail int | |
count int | |
} | |
// Push adds a item to the Queue. | |
func (q *Queue) Push(n Any) { | |
// The queue size is reached it doesn't resize. It just pops the item. | |
if q.count == q.size { | |
q.Pop() | |
} | |
q.nodes[q.backIndex()] = n | |
q.count++ | |
} | |
// Pop removes and returns the item. | |
func (q *Queue) Pop() Any { | |
if q.count == 0 { | |
return nil | |
} | |
item := q.nodes[q.head] | |
q.head = (q.head + 1) % len(q.nodes) | |
q.count-- | |
return item | |
} | |
// queue length | |
func (q *Queue) Len() int { | |
return q.count | |
} | |
func (q *Queue) backIndex() int { | |
return (q.head + q.count) % q.size | |
} | |
// creates a new instance of the queue | |
func NewQueue(size int) *Queue { | |
return &Queue{ | |
nodes: make([]Any, size), | |
size: size, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment