代码随想录 day10 第五章 栈与队列part01

今日任务:

●  理论基础

●  232.用栈实现队列

●  225. 用队列实现栈

1. 理论基础

    • 先进后出
  • 队列
    • 先进先出

2. 用栈实现队列

关联 leetcode 232.用栈实现队列

  • 两个栈模拟队列【负负得正】

    • 入栈
      • 存储队列元素
    • 出栈
      • 将入栈元素全部存储到此处,实现顺序翻转
  • 保证入栈元素全部倒出到出栈中

  • 题解

    type MyQueue struct {
    	StackInput  []int
    	StackOutput []int
    }
    
    func Constructor() MyQueue {
    	return MyQueue{
    // 利用切片实现栈,先入后出,使用append追加元素,每次出最后一个元素
    		StackInput:  make([]int, 0),
    		StackOutput: make([]int, 0),
    	}
    }
    
    // 写入只用写 入栈 即可
    func (this *MyQueue) Push(x int) {
    	this.StackInput = append(this.StackInput, x)
    }
    
    func (this *MyQueue) Pop() int {
    // 只有是 出栈 为空时,才将 入栈 全部内容写入 出栈
    	if len(this.StackOutput) == 0 {
    		lastInputIdx := len(this.StackInput) - 1
    // 可以拷贝一个入栈内容,删一个入栈数据,此处拷贝全部入栈后,清空 入栈
    		for i := lastInputIdx; i >= 0; i-- {
    			this.StackOutput = append(this.StackOutput, this.StackInput[i])
    		}
    		this.StackInput = make([]int, 0)// 拷贝完成后,清楚入栈
    	}
    
    	lastOutputIdx := len(this.StackOutput) - 1
    	res := this.StackOutput[lastOutputIdx]
    	this.StackOutput = this.StackOutput[:lastOutputIdx]//弹出元素
    
    	return res
    }
    
    func (this *MyQueue) Peek() int {
    
    	res := this.Pop()
    	this.StackOutput = append(this.StackOutput, res)
    
    	return res
    }
    
    func (this *MyQueue) Empty() bool {
    	return len(this.StackInput) == 0 && len(this.StackOutput) == 0
    }
    

3. 用队列实现栈

关联 leetcode 225. 用队列实现栈

  • 使用一个队列实现模拟栈
    • 关键操作出栈
    • 利用循环队列
      • 每次先 pop size-1个元素后,将他们重新压入队列
      • 将现在的第一个元素出队列,即是第一个出栈元素
    • top()
      • 返回队列尾部第一个元素即可
  • 题解

    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 {
    	size := len(this.Queue)
    	size -= 1
    	for size > 0 {
    		val := this.Queue[0]
    		this.Queue = this.Queue[1:]
    		this.Push(val)
    		size--
    	}
    	res := this.Queue[0]
    	this.Queue = this.Queue[1:]
    	return res
    }
    
    func (this *MyStack) Top() int {
    	return this.Queue[len(this.Queue)-1]
    }
    
    func (this *MyStack) Empty() bool {
    	return len(this.Queue) == 0
    
    }
    

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值