LeetCode力扣Golang实现/栈与队列:232、394

232 【Leetcode算法500题】目前B站最完整的数据结构算法教程,包含所有刷题攻略!这还没人看,我不更了!_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV11Y4y1q7YA?p=17

用go实现队列_枫雪月夜的博客-CSDN博客_go 队列实现https://blog.csdn.net/m15082717021/article/details/122395225

232、用栈实现队列 

为了让后入先出的栈实现先入先出的队列,需要两个栈,一个输入栈,一个输入栈

const MyArraySize = 1000

type MyStack struct {
	top  int
	data [MyArraySize]int
}

func (this *MyStack) Push(i int) bool {
	if this.top >= MyArraySize {
		return false
	}
	this.data[this.top] = i
	this.top ++
	return true
}
func (this *MyStack) Pop() (int, bool) {
	if this.top == 0 {
		return 0, false
	}
	this.top --
	n := this.data[this.top]
	return n, true
}
func (this *MyStack) Peek() int {
	if this.top == 0 {
		return -1
	}
	return this.data[this.top-1]
}

type MyQueue struct {
	input  *MyStack
	output *MyStack
}

/** Initialize your data structure here. */
func Constructor() MyQueue {
	return MyQueue{&MyStack{}, &MyStack{}}
}

/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int) {
	this.input.Push(x)

}

/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
	if this.output.top == 0 {
		this.swap()
	}
	n, _ := this.output.Pop()
	return n
}
func (this *MyQueue) swap()  {
	for {
		i, ok := this.input.Pop()
		if !ok {
			break
		}
		this.output.Push(i)
	}
}
/** Get the front element. */
func (this *MyQueue) Peek() int {
	if this.output.top == 0 {
		this.swap()
	}
	return this.output.Peek()
}

/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
	if this.input.top == 0 && this.output.top == 0 {
		return true
	}
	return false
}

?Q:对于mystack的pop操作如果没有值不应该返回空吗,为什么是0

而且对于出栈后,这个位置的元素需不需要清空,为啥结果一样,清空为nil不行,0的话不就白占数字

为什么栈不用初始化但是队列要

394、字符串解码 

用栈:1.linkedlist或者stack

每当遇到数字需要单独处理:有可能是多位数字

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值