代码随想录算法训练营day10| 232.用栈实现队列 225. 用队列实现栈

232.用栈实现队列

包含使用数组模拟栈,使用两个栈模拟队列两个知识点,其中后者分为输入栈和输出栈,动态地处理元素,非常巧妙

type MyStack struct {
	elements []int // 存放元素的数组
}

// 判断栈是否为空
func (this *MyStack) isEmpty() bool {
	return this.size() == 0
}
func (this *MyStack) push(element int) {
	this.elements = append(this.elements, element)
}
func (this *MyStack) pop() int {
	lastElement := this.elements[this.size()-1]
	this.elements = this.elements[:this.size()-1]
	return lastElement
}
func (this *MyStack) top() int {
	return this.elements[this.size()-1]
}
func (this *MyStack) size() int {
	return len(this.elements)
}

type MyQueue struct {
	inputStack  *MyStack
	outputStack *MyStack
}

func Constructor() MyQueue {
	inputStack, outputStack := new(MyStack), new(MyStack)
	return MyQueue{inputStack, outputStack}
}
func (this *MyQueue) Push(x int) {
	this.inputStack.push(x)
}

func (this *MyQueue) Pop() int {
	if this.outputStack.isEmpty() {
		for this.inputStack.isEmpty() == false {
			this.outputStack.push(this.inputStack.pop())
		}
	}
	return this.outputStack.pop()
}

func (this *MyQueue) Peek() int {
	if this.outputStack.isEmpty() {
		for this.inputStack.isEmpty() == false{
			this.outputStack.push(this.inputStack.pop())
		}
	}
	return this.outputStack.top()
}

func (this *MyQueue) Empty() bool {
	return this.outputStack.size() + this.inputStack.size() == 0
}

225. 用队列实现栈

包含go中模拟队列和单队列模拟栈两个考点,单队列模拟栈的思路是将队列头元素删除后重新入队,直到最后一个元素到达头部,来实现pop操作

type MyQueue struct{
	elements []int  // 存放元素的数组
}

func (this *MyQueue) Size() int{
	return len(this.elements)
}

func (this *MyQueue) Enqueue(x int) {
	// 进入队列
	this.elements = append(this.elements, x)	
}

func (this *MyQueue) Dequeue() int {
	// 弹出队列
	element := this.elements[0]
	this.elements = this.elements[1:this.Size()]
	return element
}

func (this *MyQueue) Peek() int {
	// 获取队列头部元素
	return this.elements[0]
}

type MyStack struct {
	myQueue *MyQueue	
}

func Constructor() MyStack {
	myQueue := new(MyQueue)
	return MyStack{myQueue}
}


func (this *MyStack) Push(x int)  {
	this.myQueue.Enqueue(x)
}


func (this *MyStack) Pop() int {
	for index :=0 ;index < this.myQueue.Size() - 1;index++{
		this.myQueue.Enqueue(this.myQueue.Dequeue())	
	}
	return this.myQueue.Dequeue()
}


func (this *MyStack) Top() int {
	element := this.Pop()
	this.Push(element)
	return element
}


func (this *MyStack) Empty() bool {
	return this.myQueue.Size() == 0
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值