手写!!!
225. 用队列实现栈
使用队列实现栈的下列操作:
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
type MyStack struct {
Items []int
}
/** Initialize your data structure here. */
func Constructor() MyStack {
return MyStack{ Items:[]int{} }
}
/** Push element x onto stack. */
func (this *MyStack) Push(x int) {
this.Items = append(this.Items, x)
}
func (this *MyStack) Pop() int {
if this.Empty() {
return 0
}
temp := this.Items[len(this.Items)-1]
this.Items = this.Items[0 :len(this.Items) -1]
return temp
}
/** Get the top element. */
func (this *MyStack) Top() int {
if !this.Empty() {
return this.Items[len(this.Items) - 1]
}
return 0
}
/** Returns whether the stack is empty. */
func (this *MyStack) Empty() bool {
if len(this.Items) <= 0 {
return true
}
return false
}
面试题09. 用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
type CQueue struct {
//栈in负责输入,栈out负责从头输出
in []int
out []int
}
func Constructor() CQueue {
return CQueue{
//为两个栈预申请空间,减少内存消耗
make([]int,0,5),
make([]int,0,5),
}
}
func (this *CQueue) AppendTail(value int) {
if value<1 && value>10000{
return
}else{
this.in = append(this.in[:], value)
}
}
核心代码
常规逻辑
func (this *CQueue) DeleteHead() int {
// 两个栈都为空
if len(this.out) == 0 && len(this.in) == 0 {
return -1
}
// out 栈为空,依次弹出 in 栈栈顶元素,入 out 栈
if len(this.out) == 0 {
for len(this.in) > 0 {
lastIndex := len(this.in) - 1
popValue := this.in[lastIndex]
this.in = this.in[:lastIndex]
this.out = append(this.out, popValue)
}
}
// 弹出 out 栈顶元素
lastIndex := len(this.out) - 1
popValue := this.out[lastIndex]
this.out = this.out[:lastIndex]
return popValue
}
另一种解法
func (this *CQueue) DeleteHead() int {
//情况1:无人进栈
if len(this.in)==0{
return -1
}
//情况2:出入相等
if len(this.in)==len(this.out){
return -1
}
// 这个写法输出正确答案,但并没有改变原栈的值
out:=this.in[len(this.out)]
this.out=append(this.out[:],this.in[len(this.out)])
return out
}