go int 转char_GO语言实现 一 栈和队列
生活随笔
收集整理的這篇文章主要介紹了
go int 转char_GO语言实现 一 栈和队列
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
線性表中,棧和隊列是非常重要的兩種數(shù)據(jù)結(jié)構(gòu),本文將就這兩種數(shù)據(jù)結(jié)構(gòu)進行 golang語言實現(xiàn)
參考:go語言中文文檔:www.topgoer.com
轉(zhuǎn)自:https://www.jianshu.com/p/e8de9ac93cbc
一.棧的實現(xiàn)
我們需要實現(xiàn)如下幾個方法
我們需要注意 peer() 方法并不會將棧頂元素刪除
數(shù)組實現(xiàn)如下:
type stack struct { cache []int}func (sk *stack) push(n int) { sk.cache = append(sk.cache, n)}func (sk stack) length() int { return len(sk.cache)}func (sk *stack) pop() int { if sk.length() == 0 { return 0 } item := sk.cache[sk.length()-1] sk.cache = sk.cache[:len(sk.cache)-1] return item}func (sk stack) isEmpty() bool { return len(sk.cache) == 0}func (sk stack) peer() int { return sk.cache[sk.length()-1]}接下來,我們將用鏈表實現(xiàn)以下項目,并使用 interface{} 來代替 int實現(xiàn)多種類型的兼容
type stackLink struct { Top *node Length int}type node struct { Val interface{} Prev *node}func (sl *stackLink) push(value interface{}) { newNode := &node{ Val: value, Prev: sl.Top} sl.Top = newNode sl.Length++}func (sl *stackLink) pop() interface{} { topNodeVal := sl.Top.Val sl.Top = sl.Top.Prev sl.Length-- return topNodeVal}func (sl stackLink) length() int { return sl.Length}func (sl stackLink) isEmpty() bool { return sl.Length == 0}func (sl stackLink) peer() interface{} { return sl.Top.Val}由于任何的變量都實現(xiàn)了空接口,所以我們可以通過傳遞空接口來實現(xiàn)在棧中壓入不同元素的目的
二.隊列實現(xiàn)
同樣,我們對于隊列,實現(xiàn)了如下方法:
鏈表實現(xiàn)方式如下:
type queue struct { First *node Last *node Len int}type node struct { Val interface{} Next *node Pre *node}func (qu *queue) enqueue(data interface{}) { nNode := &node{ Val: data, Pre: qu.First, Next: nil} if qu.First == nil { qu.First = nNode } else { qu.First.Next = nNode qu.First = nNode } if qu.Last == nil { qu.Last = nNode } qu.Len++}func (qu *queue) dequeue() interface{} { if qu.Len > 0 { nNode := qu.Last.Val if qu.Last.Next != nil { qu.Last.Next.Pre = nil } qu.Last = qu.Last.Next qu.Len-- return nNode } return errors.New("error")}func (qu queue) isEmpty() bool { return qu.Len <= 0}func (qu queue) getLength() int { return qu.Len}三.棧和隊列的應(yīng)用
在這一部分,我們通過棧來實現(xiàn)表達(dá)式的計算
例如:我們需要計算 (1+((2+3)*(4*5)))
我們維護兩個棧,一個是值棧,一個是操作棧,我們在讀取表達(dá)式的時候采取如下的策略:
我們?nèi)缦抡{(diào)用
stackCompute("(1+((2+3)*(4*5)))")將會得到結(jié)果 101總結(jié)
以上是生活随笔為你收集整理的go int 转char_GO语言实现 一 栈和队列的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: skywalking 安装_SkyWal
- 下一篇: React Hooks的使用(三)——u