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"]
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末鼻百,一起剝皮案震驚了整個(gè)濱河市绞旅,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌温艇,老刑警劉巖因悲,帶你破解...
    沈念sama閱讀 211,123評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異勺爱,居然都是意外死亡晃琳,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,031評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門琐鲁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)卫旱,“玉大人,你說(shuō)我怎么就攤上這事围段」艘恚” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 156,723評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵奈泪,是天一觀的道長(zhǎng)适贸。 經(jīng)常有香客問(wèn)我,道長(zhǎng)涝桅,這世上最難降的妖魔是什么拜姿? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,357評(píng)論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮冯遂,結(jié)果婚禮上蕊肥,老公的妹妹穿的比我還像新娘。我一直安慰自己债蜜,他們只是感情好晴埂,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,412評(píng)論 5 384
  • 文/花漫 我一把揭開(kāi)白布究反。 她就那樣靜靜地躺著,像睡著了一般儒洛。 火紅的嫁衣襯著肌膚如雪精耐。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 49,760評(píng)論 1 289
  • 那天琅锻,我揣著相機(jī)與錄音卦停,去河邊找鬼。 笑死恼蓬,一個(gè)胖子當(dāng)著我的面吹牛惊完,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播处硬,決...
    沈念sama閱讀 38,904評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼小槐,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了荷辕?” 一聲冷哼從身側(cè)響起凿跳,我...
    開(kāi)封第一講書(shū)人閱讀 37,672評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎疮方,沒(méi)想到半個(gè)月后控嗜,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,118評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡骡显,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,456評(píng)論 2 325
  • 正文 我和宋清朗相戀三年疆栏,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片惫谤。...
    茶點(diǎn)故事閱讀 38,599評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡壁顶,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出石挂,到底是詐尸還是另有隱情博助,我是刑警寧澤,帶...
    沈念sama閱讀 34,264評(píng)論 4 328
  • 正文 年R本政府宣布痹愚,位于F島的核電站富岳,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏拯腮。R本人自食惡果不足惜窖式,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,857評(píng)論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望动壤。 院中可真熱鬧萝喘,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,731評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至启妹,卻和暖如春筛严,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背饶米。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,956評(píng)論 1 264
  • 我被黑心中介騙來(lái)泰國(guó)打工桨啃, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人檬输。 一個(gè)月前我還...
    沈念sama閱讀 46,286評(píng)論 2 360
  • 正文 我出身青樓照瘾,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親丧慈。 傳聞我的和親對(duì)象是個(gè)殘疾皇子析命,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,465評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,306評(píng)論 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    網(wǎng)事_79a3閱讀 11,916評(píng)論 3 20
  • 這是發(fā)生在名為終焉的大陸上的故事,這是有關(guān)第三次諸神黃昏的故事伊滋,這是惡魔與人類的故事碳却,這是少年與少女的故事。 ...
    藥糖執(zhí)筆閱讀 213評(píng)論 0 0
  • (顧城) 我喜歡穿舊衣裳在默默展開(kāi)的早晨里穿過(guò)廣場(chǎng)一蓬蓬郊野的荒草從縫隙中無(wú)聲地爆發(fā)起來(lái)我不能停留那些瘦小的黑蟋蟀...
    紫章閱讀 503評(píng)論 0 4
  • 我本來(lái)是在微博發(fā)每日的笑旺!但是突然要驗(yàn)證手機(jī),試了兩天了收不到驗(yàn)證碼馍资!于是非常生氣但是練習(xí)不能斷呀M仓鳌(不遮了反正看不...
    syeturing閱讀 172評(píng)論 0 0