棧 佇列 遞迴 演算法的GO語言實現

2022-05-17 16:29:23 字數 1743 閱讀 3236

//用陣列實現乙個順序棧

type stack struct

func newstack(capicity int) *stack

stack.arr = make(int,capicity)

stack.used = 0

stack.capcity = capicity

return stack

}// 入棧操作

func (this *stack)push(item int)bool

// 將item放到下標為used的位置,並且used加一

this.arr[this.used] = item

this.used++

return true

}// 出棧操作

func (this *stack)pop() int

// 返回下標為used-1的陣列元素,並且棧中元素個數used減一

tmp := this.arr[this.used-1]

this.used--

return tmp

}/**

用哨兵鍊錶實現乙個順序棧

*/type node struct

type stack struct

//初始化的時候建立乙個空的帶頭節點

func newstack()*stack

newnode := &node{}

stack.top = newnode

return stack

}//入棧

func (this *stack)push(value int) bool

newnode.value = value

//直接把頭節點複製給新節點然後把新節點指向到頭節點

newnode.next = this.top.next

this.top.next = newnode

return true

}//出棧

func (this *stack)pop() int

//獲取第乙個非帶頭節點的值,並且把指標往後移

tmp := this.top.next.value

this.top.next = this.top.next.next

return tmp

}

/**

用陣列實現乙個順序佇列

*/type queue struct

func newqueue(capicity int)*queue

queue.arr = make(int,capicity)

queue.head = 0

queue.tail = 0

queue.capicity = capicity

return queue

}func (this *queue)push(value int) bool

//把資料批量往前移動

for i:=this.head; i1 1,2=>[2,1][1,2]

//遞推公式:print n,funarr(arr,n+1)

//遞迴結束條件:陣列結束n == arr[len-1]

//length個數(無重)的全排列,就是將length個數分別放在第零個位置,再將剩下的length-1個數的全排列加在後面,當length-1=1時為遞迴的出口

func funarr(arr int,n int,length int)else

}}

演算法總結 棧 佇列 c語言實現

還是一道題typedef struct node1 d typedef struct node2 z d d1,d2 z z 初始化佇列d1和d2,此時兩人手中沒有牌 d1.head 0 d1.tail 0 d2.head 0 d2.tail 0 初始化棧z為空,最開始桌面上也沒有牌 z.top 0...

棧,佇列的C語言實現

棧的c語言實現 佇列的c語言實現 棧 後進先出 允許插入和刪除的一端叫棧頂top 不允許的一端叫棧底bottom 主要操作 進棧 出棧 判斷棧滿和棧空 有兩個現成的函式 int push int s,int x,int ptop int pop int s,int py,int ptop 直接拿過來...

go語言實現順序儲存的棧

1.sequence.go 如下 複製 如下 順序儲存的棧 package sequence const maxsize 20 type stack struct 壓棧 d 棧元素 func s stack push d int bool s.data s.top 1 d s.top return ...