Implementation of Some Commonly Used Data Structures in Go

Some data structures are commonly used in our development, such as stack, queue, map, etc.. However, (I think) the philosophy of Go is as simple as possible. Go doesn't provide some data structures that I think it should have. Of course I know Go has slice and map but it's the unbox-and-use thing that makes our life simpler, isn't it?

Sometimes I am super disappointed that the lack of stack, queue, set and sorted map in Go so here I am. I try to implement the four data structures I just mention.

If there is something wrong, feel free to point it out and I, a newbie of Go, will be very thankful. :smiley:

Stack

// A simple implementation of stack.
type Stack struct {
    // the data stored in stack
    elements []interface{}
}

// Construct a new stack.
func NewStack() *Stack {
    return &Stack{make([]interface{}, 0)}
}

// Test if the stack is empty.
func (s *Stack) Empty() bool {
    return len(s.elements) == 0
}

// Return the size of stack.
func (s *Stack) Size() int {
    return len(s.elements)
}

// Push an item into the top of stack.
func (s *Stack) Push(e interface{}) interface{} {
    s.elements = append(s.elements, e)
    return e
}

// Remove the top of stack and return it.
func (s *Stack) Pop() interface{} {
    if s.Empty() {
        return nil
    }
    v := s.elements[len(s.elements)-1]
    s.elements = s.elements[:len(s.elements)-1]
    return v
}

// Retrieve the top of stack.
func (s *Stack) Peek() interface{} {
    if s.Empty() {
        return nil
    }
    return s.elements[len(s.elements)-1]
}

Example

func main() {
    s := NewStack()
    for i := 0; i < 10; i++ {
        s.Push(i)
    }
    fmt.Println(s.Size()) // output: 10
    top := s.Peek()
    fmt.Println(top)  // output: 9
    for !s.Empty() {
        fmt.Println(s.Pop())  // output: 9 8 7 6 5 4 3 2 1 0
    }
}

Notice that in the Popmethod, I use s.elements = s.elements[:len(s.elements)-1]to remove the last element from slice. Actually it's a trick as mentioned in this article.

Queue

// A simple implementation of Queue.
type Queue struct {
    // the data stored in queue
    elements []interface{}
}

// Construct a new queue.
func NewQueue() *Queue {
    return &Queue{make([]interface{}, 0)}
}

// Test if the queue is empty.
func (q *Queue) Empty() bool {
    return len(q.elements) == 0
}

// Return the size of queue.
func (q *Queue) Size() int {
    return len(q.elements)
}

// Add an item to the tail of queue.
func (q *Queue) Add(e interface{}) interface{} {
    q.elements = append(q.elements, e)
    return e
}

// Remove the head of queue and return it.
func (q *Queue) Poll() interface{} {
    if q.Empty() {
        return nil
    }
    v := q.elements[0]
    q.elements = q.elements[1:]
    return v
}

// Retrieve the head of queue and return it.
func (q *Queue) Peek() interface{} {
    if q.Empty() {
        return nil
    }
    return q.elements[0]
}

Example

func main() {
    q := NewQueue()
    for i:= 0; i < 10; i++ {
        q.Add(i)
    }    
    fmt.Println(q.Size()) // output: 10
    head := q.Peek()
    fmt.Println(head) // output: 0
    for !q.Empty() {
        fmt.Println(q.Poll()) // output: 0 1 2 3 4 5 6 7 8 9
    }
}

Set

// A simple implementation of set.
type Set struct {
    // key: data stored in set
    // value: whether data exists in set
    elements map[interface{}]bool
}

// Construct a new set.
func NewSet() *Set {
    return &Set{make(map[interface{}]bool)}
}

// Return the size of set.
func (s *Set) Size() int {
    return len(s.elements)
}

// Test if the set is empty.
func (s *Set) Empty() bool {
    return len(s.elements) == 0
}

// Add an item that doesn't exist into set. 
// If the set didn't contain the item, return true, 
func (s *Set) Add(e interface{}) bool {
    if ok := s.elements[e]; !ok {
        s.elements[e] = true
        return true
    } else {
        return false
    }
}

// Remove the specific item if it exists in the set.
// Return true if the set contained the specified item
func (s *Set) Remove(e interface{}) bool {
    if ok := s.elements[e]; !ok {
        return false
    } else {
        delete(s.elements, e)
        return true
    }
}

// Test if a specific item exists in the set.
func (s *Set) Contains(e interface{}) bool {
    return  s.elements[e]
}

// Return all items in the set.
func (s *Set) Values() []interface{} {
    vals := make([]interface{}, 0, len(s.elements))
    for v, ok := range s.elements {
        if ok {
            vals = append(vals, v)
        }
    }
    return vals
}

Example

func main() {
    set := NewSet()
    set.Add(1)
    set.Add(2)
    set.Add(3)
    set.Add(3)
    fmt.Println(set.Contains(1)) // output: true
    set.Remove(2)
    for e := set.values() {
        fmt.Println(e) // output: 1 3
    } 
}

I want to point out that the idea of implementing a set based on a map whose value type is boolis mentioned in Effective Go.

Sorted Map

I have to admit that one of the biggest disadvantage of Go is the lack of generics (another one may be the lack of a mature dependency management tool). I can't generalize the solution because I have to specify a sortable type as key type. Here I just implement the sorted map of intkey.

// A simple implementation of sorted map.
type SortedMapInt struct {
    // all key-value pairs
    pairs map[int]interface{}
    // keys in their natural order
    keys []int
}

// Construct a new sorted map.
func NewSortedMapInt() *SortedMapInt {
    return &SortedMapInt{make(map[int]interface{}), make([]int, 0)}
}

// Test if the map is empty.
func (m *SortedMapInt) Empty() bool {
    return len(m.pairs) == 0
}

// Put a new key-value pair into the map and return the old 
// associated value of this key or nil if there was no mapping for key.
func (m *SortedMapInt) Put(k int, v interface{}) interface{} {
    if _, ok := m.pairs[k]; !ok {
        m.keys = append(m.keys, k)
        sort.Ints(m.keys)
    }
    old := m.pairs[k]
    m.pairs[k] = v
    return old
}

// Return the associated value of a specific key if the key exists.
func (m *SortedMapInt) Get(k int) interface{} {
    if v, ok := m.pairs[k]; ok {
        return v
    } else {
        return nil
    }
}

// Remove the associated value of a specific key if the key exists.
func (m *SortedMapInt) Remove(k int) interface{} {
    if v, ok := m.pairs[k]; ok {
        delete(m.pairs, k)
        return v
    } else {
        return nil
    }
}

// Return the set of keys in their natural order.
func (m *SortedMapInt) Keys() []int {
    return m.keys
}

// Return the set of associated values of sorted keys.
func (m *SortedMapInt) Values() []interface{} {
    vals := make([]interface{}, 0)
    for _, k := range m.keys {
        if v, ok := m.pairs[k]; ok {
            vals = append(vals, v)
        }
    }
    return vals
}

Example

func main() {
    sMap := NewSortedMapInt()
    sMap.Put(1, "a")
    sMap.Put(2. "b")
    sMap.Put(3, "c")
    sMap.Put(1, "d")
    fmt.Println(sMap.Keys()) // output: [1 2 3]
    sMap.Remove(2)
    fmt.Println(sMap.Values()) // output: ["d" "c"]
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,254评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 11,497评论 2 19
  • 这是发生在名为终焉的大陆上的故事,这是有关第三次诸神黄昏的故事,这是恶魔与人类的故事,这是少年与少女的故事。 ...
    药糖执笔阅读 211评论 0 0
  • (顾城) 我喜欢穿旧衣裳在默默展开的早晨里穿过广场一蓬蓬郊野的荒草从缝隙中无声地爆发起来我不能停留那些瘦小的黑蟋蟀...
    紫章阅读 503评论 0 4
  • 我本来是在微博发每日的!但是突然要验证手机,试了两天了收不到验证码!于是非常生气但是练习不能断呀!(不遮了反正看不...
    syeturing阅读 169评论 0 0