資料結構之堆疊
一、入堆疊
package main
import (
"fmt"
"errors"
)
type Stack struct{
maxTop int
Top int
arr [5]int
}
func (this *Stack) Push(val int)(err error){
if this.Top==this.maxTop-1{
return errors.New("Stack full")
}
this.Top++
this.arr[this.Top]=val
return
}
func (this *Stack) Show(){
if this.Top==-1{
fmt.Println("堆疊為空...")
return
}
for i:=this.Top;i>-1;i--{
fmt.Printf("arr[%d]=%d\n",i,this.arr[i])
}
}
func main(){
stack:=&Stack{
maxTop:6,
Top:-1,
}
stack.Push(1)
stack.Push(2)
stack.Push(3)
stack.Push(4)
stack.Push(5)
stack.Show()
}
二、出堆疊
func (this *Stack) Pop()(val int,err error){
if this.Top==-1{
fmt.Println("Stack full")
return
}
val=this.arr[this.Top]
this.Top--
return
}
三、堆疊實作計算器
計算3+2*6-2這個算式

首先借鑒上述堆疊的Pop和Push,這里還需要添加一些底層的函式(判斷是否為符號,比較優先級,計算函式)
//設定判斷運算子的函式
func (this *Stack) Isoper(val int) bool{
if val==42||val==45||val==43||val==47{
return true
}else{
return false
}
}
//設定計算值的函式
func(this *Stack) cal(num1 int,num2 int,oper int)int{
var res int
switch oper{
case 43:
res=num1+num2
case 45:
res=num1-num2
case 42:
res=num1*num2
case 47:
res=num1/num2
default:
fmt.Println("運算子發生錯誤")
}
return res
}
//優先級的判斷
func (this *Stack) Priority(oper int)int{
var res int
if oper==42||oper==47{
res=1
}else if oper==43||oper==45{
res=0
}
return res
}
主函式程式:
func main(){
numStack:=&Stack{
maxTop:20,
Top:-1,
}
operStack:=&Stack{
maxTop:20,
Top:-1,
}
exp:="3+2*6-4"
index:=0
num1:=0
num2:=0
res:=0
oper:=0
for{
ch:=exp[index:index+1]
temp:=int([]byte(ch)[0]) //轉換為Acall
if operStack.Isoper(temp){ //判斷是否為符號
if operStack.Top==-1{ //堆疊為空
operStack.Push(temp)
}else if operStack.First(operStack.arr[operStack.Top])>=operStack.First(temp){//堆疊頂元素優先級大于等于輸入的
num1,_=numStack.Pop()
num2,_=numStack.Pop()
oper,_=operStack.Pop()
res=operStack.cal(num2,num1,oper)
numStack.Push(res) //計算結果壓入
operStack.Push(temp)//將符號壓入
}else{
operStack.Push(temp)//將計算結果壓入
}
}else{
val,_:=strconv.ParseInt(ch,10,64)
numStack.Push(int(val))
}
if index+1==len(exp){
break
}else{
index++
}
}
for{
num1,_=numStack.Pop()
num2,_=numStack.Pop()
oper,_=operStack.Pop()
res=operStack.cal(num2,num1,oper)
numStack.Push(res)
if operStack.Top==-1{
break
}
}
res,_=numStack.Pop()
fmt.Printf("計算%s的結果為%d",exp,res)
}
由于可能存在30+2*6-2這種算式,連續兩個數字,所以上述的代碼只能計算個位數字,需要在判斷為數字的時候進行改進
else{
//增加判斷是不是連續數字的陳述句
//設定變數keepNum來累加
keepNum+=ch
//首先判斷是否是最后一個數字,如果是,直接Push
if index==len(exp)-1{
val,_:=strconv.ParseInt(keepNum,10,64)
numStack.Push(int(val))
}else{ //判斷是否有連續數字
if operStack.Isoper(int([]byte(exp[index+1:index+2])[0])){
val,_:=strconv.ParseInt(keepNum,10,64)
numStack.Push(int(val))
keepNum=""
}
}
}
這樣累加后就可以得出多位數的演算法
看完這篇文章如果對自己有幫助,請點贊支持,謝謝
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/266421.html
標籤:區塊鏈
