题解 | 用两个栈实现队列
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
package main
var stack1 []int
var stack2 []int
func Push(node int) {
stack1 = append(stack1, node)
}
func Pop() int {
for len(stack1) > 0 {
tmp := stack1[0]
stack1 = stack1[1:] // stack1 pop
stack2 = append(stack2, tmp) // stack2 push
}
res := stack2[0]
stack2 = stack2[1:] // stack2 pop
for len(stack2) > 0 {
tmp := stack2[0]
stack2 = stack2[1:] // stack2 pop
stack1 = append(stack1, tmp) // stack1 push
}
return res
}

查看14道真题和解析