【代码随想录】算法训练计划10

1、232. 用栈实现队列

题目:
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false

思路:
  • 双栈模拟法,注意拿的是栈顶元素,拿完更新长度
// 代码一刷,很多细节需要注意
type MyQueue struct {
    stackIn []int
    stackOut []int
}

// 作用就是初始化一个队列,的对象
func Constructor() MyQueue {
    return MyQueue{
        stackIn: make([]int, 0),
        stackOut: make([]int, 0),
    }
}


func (this *MyQueue) Push(x int)  {
    this.stackIn = append(this.stackIn, x)
}


func (this *MyQueue) Pop() int {
    // 最核心的最难的——把入栈元素都给放到out栈
    inLen, outLen := len(this.stackIn), len(this.stackOut)
    if outLen == 0 {
        if inLen == 0 {
            return -1
        }
        for i:=inLen-1; i>=0; i-- { //拿栈顶元素
            this.stackOut = append(this.stackOut, this.stackIn[i])
        }
        this.stackIn = []int{} // 清空,因为都赋值过了,别忘了
        outLen = len(this.stackOut) // 更新长度,否则又进入循环
    }
    val := this.stackOut[outLen-1] // 拿到栈顶元素值
    this.stackOut =  this.stackOut[:outLen-1] // 出栈
    return val
}


func (this *MyQueue) Peek() int {
    val := this.Pop() // 出栈了
    if val == -1 {
        return -1
    }
    this.stackOut = append(this.stackOut, val) //但题意是返回开头元素,并没说让你出去,所以就再加回来
    return val
}


func (this *MyQueue) Empty() bool {
    return len(this.stackIn) == 0 && len(this.stackOut) == 0
}

2、225. 用队列实现栈

题目:

思路:
  • 一个队列,n-1个元素再次放入队列队尾即可
// 代码一刷
type MyStack struct {
    queue []int
}


func Constructor() MyStack {
    return MyStack{
        queue: make([]int, 0),
    }
}


func (this *MyStack) Push(x int)  {
    this.queue = append(this.queue, x)
}


func (this *MyStack) Pop() int {
    // 又来到了最难的地方
    n := len(this.queue)-1
    for n!=0 {
        val := this.queue[0] // 拿到栈顶元素
        this.queue = this.queue[1:]
        this.queue = append(this.queue, val)
        n--
    }
    val := this.queue[0]
    this.queue = this.queue[1:]
    return val
}


func (this *MyStack) Top() int {
    // 当成栈就行
    val := this.Pop()
    this.queue = append(this.queue, val)
    return val
}


func (this *MyStack) Empty() bool {
    return len(this.queue)==0
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不之道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值