4.5 优化其实这道题目就是用一个队列就够了 。
一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时在去弹出元素就是栈的顺序了 。
4.6 使用一个队列实现type MyStack struct { queue []int//创建一个队列}/** Initialize your data structure here. */func Constructor() MyStack { return MyStack{ //初始化 queue:make([]int,0), }}/** Push element x onto stack. */func (this *MyStack) Push(x int) { //添加元素 this.queue=append(this.queue,x)}/** Removes the element on top of the stack and returns that element. */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}/** Get the top element. */func (this *MyStack) Top() int { //利用Pop函数,弹出来的元素重新添加 val:=this.Pop() this.queue=append(this.queue,val) return val}/** Returns whether the stack is empty. */func (this *MyStack) Empty() bool { return len(this.queue)==0}
经验总结扩展阅读
- 正官格女命与什么命格最配 感情婚姻天长地久
- 正官格女命配什么男命好与正财格男最适配
- 属虎三合和三冲属相 生肖配对的喜与忌
- 戊土男和庚金女的姻缘 感情与日俱增甜蜜
- 白蜡金命与什么命相配最合婚 强旺命格互相弥补
- 定位java程序中占用cpu最高的线程堆栈信息
- 自己动手实现线程池 jdk线程池ThreadPoolExecutor工作原理解析(一)
- 活虾怎么处理干净虾线
- 92年属猴女最佳婚配 92年女属猴与什么婚配
- 大海水命与石榴木命 婚姻合不合