LeetCode(集合)队列和栈的相互实现 golang

手写!!!

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
}

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值