代码如下
type MyQueue struct {
stack []int //stack为进数组
back []int //back为出数组
}
func Constructor() MyQueue {
return MyQueue {
stack : make([]int,0), //初始化
back : make([]int,0),
}
}
func (this *MyQueue) Push(x int) {
for len(this.back) != 0 { //这里的思路是,如果出数组里面还有元素,那么进新的元素的时候,为了满足队列的性质,需要先将停留在出数组里的元素全部压入进数组,然后再进新的元素
val := this.back[len(this.back)-1]
this.back = this.back[:len(this.back)-1]
this.stack = append(this.stack,val)
}
this.stack = append(this.stack,x)
}
func (this *MyQueue) Pop() int {
for len(this.stack) != 0 { //同理,当要出元素的时候,需要将进数组中所有的元素压入出数组
val := this.stack[len(this.stack)-1]
this.stack = this.stack[:len(this.stack)-1]
this.back = append(this.back,val)
}
if len(this.back) == 0 {
return 0
}
val := this.back[len(this.back)-1]
this.back = this.back[:len(this.back)-1]
return val
}
func (this *MyQueue) Peek() int { //队列顶元素就是出数组的最后一个元素
val := this.Pop()
this.back = append(this.back,val)
return val
}
func (this *MyQueue) Empty() bool {
if len(this.stack) == 0 && len(this.back) == 0 {
return true
}else {
return false
}
}
225 用队列实现栈
type MyStack struct {
queue1 []int
queue2 []int
}
func Constructor() MyStack {
return MyStack {
queue1 : make([]int,0),
queue2 : make([]int,0),
}
}
func (this *MyStack) Push(x int) {
this.queue2 = append(this.queue2,x) //先将元素压入队列2 中
for len(this.queue1) > 0 { //如果队列1里面有元素,先将队列1里的所有元素压入队列2中
this.queue2 = append(this.queue2,this.queue1[0])
this.queue1 = this.queue1[1:]
}
this.queue1,this.queue2 = this.queue2,this.queue1 然后交换队列1和2
}
func (this *MyStack) Pop() int {
val := this.queue1[0] //弹出队列1中的首个元素
this.queue1 = this.queue1[1:]
return val
}
func (this *MyStack) Top() int {
return this.queue1[0]
}
func (this *MyStack) Empty() bool {
if len(this.queue1) == 0 {
return true
}else {
return false
}
}
20 有效的括号
代码如下
func isValid(s string) bool {
hash := map[byte]byte{')':'(','}':'{',']':'['} 先定义一个map,map的key是右括号,value是左括号
stack := make([]byte,0) 定义一个存放元素的数组
if s == "" {
return true
}
for i := 0 ; i < len(s) ; i++ {
if s[i] == '(' || s[i] == '{' || s[i] == '[' { //遇到左括号就放入数组中
stack = append(stack,s[i])
}else if len(stack) > 0 && stack[len(stack)-1] ==hash[s[i]] { //如果放入的是右括号就要进行判断,且这个存放栈中有元素。那么需要先用之前的map将右括号转换为对应的左括号,并将这个与栈中最后一个元素做对比,如果匹配,则消掉栈中最后一个元素,如果不匹配则说明右括号没有对应上左括号,返回false。如果栈为空的时候输入右括号直接返回false
stack = stack[:len(stack)-1]
}else {
return false
}
}
if len(stack) == 0 { //遍历完成后,如果stack里还有左括号,那么就返回false
return true
}else {
return false
}
}