This is a creation in Article, where the information may have evolved or changed.
Golang stack, queue implementation and common operations, data structure Series original: Flaviocopes.com, translation has been authorized by the author.
Stack
Overview
A stack is a collection of data in the LIFO (last-in-first-out) principle. Adding and removing elements is done at the top of the stack, analogy to the book heap, cannot add or remove elements at the bottom of the stack.
The application of the stack is very wide, such as the page after the jump layer back, CTRL + Z undo operation.
Using a slice dynamic type to implement the stack, the type of the stack element is a common type created using Genny ItemStack , which implements the following common operations:
1 2 3
|
New ()//constructor for build stack Push () Pull ()
|
Code implementation
1 2 3 4 5 6 7 8 9 Ten One A - - the - - - + - + A at - - - - - in - to + - the *
|
Package Stack
Import ( "Github.com/cheekybits/genny/generic" "Sync" )
type Item generic. Type
type itemstack struct { items []item lock Sync. Rwmutex }
//Create stacks func (S *itemstack) New() *itemstack { s.items = []item{} return s }
//into the stack func (S *itemstack) Push(t Item) { S.lock.lock () s.items = Append(s.items, T) S.lock.unlock () }
//out of Stack func (S *itemstack) Pop() *Item { S.lock.lock () Item: = s.items[len(s.items)-1] s.items = s.items[:len(s.items)-1 ] S.lock.unlock () return &item }
|
Test Case: Stack_test.go
Queue
Overview
A queue is a collection of data in the first-in FIFO (first-in-first-out) principle, an analogy that queues up, adds elements at either end of the queue, and removes elements from the opposite end.
Using a slice dynamic type to implement a queue, the type of the element is a generic type ItemQueue , and the following common operations are implemented:
1 2 3 4 5 6
|
New ()//constructor for build queue Enqueue () Dequeue () Front () IsEmpty () Size ()
|
Code implementation
1 2 3 4 5 6 7 8 9 Ten One A - - the - - - + - + A at - - - - - in - to + - the * $ Panax Notoginseng - the + A the + - $ $ - - the - Wuyi the -
|
Package Queue
Import ( "Github.com/cheekybits/genny/generic" "Sync" )
type Item generic. Type
type itemqueue struct { items []item lock Sync. Rwmutex }
//Create a queue func (q *itemqueue) New() *itemqueue { q.items = []item{} return q }
//such as Queues func (q *itemqueue) Enqueue(t Item) { Q.lock.lock () q.items = Append(q.items, T) Q.lock.unlock () }
//OUT queue func (q *itemqueue) Dequeue() *Item { Q.lock.lock () Item: = q.items[0] Q.items = q.items[1:len(q.items)] Q.lock.unlock () return &item }
//Gets the first element of the queue, does not remove func (q *itemqueue) Front() *Item { Q.lock.lock () Item: = q.items[0] Q.lock.unlock () return &item }
//Empty func (q *itemqueue) IsEmpty() bool { return len(q.items) = = 0 }
//Gets the length of the queue func (q *itemqueue) Size() int { return len(q.items) }
|
Test Case: Queue_test.go