学习时间:
晚上七点-晚上八点
理论基础
232.用栈实现队列
思路:
使用栈来模式队列的行为,如果仅仅用一个栈,是一定不行的,所以需要两个栈一个输入栈,一个输出栈,这里要注意输入栈和输出栈的关系。
代码实现:
class MyQueue {
constructor() {
this.stackIn = [];
this.stackOut = [];
}
push (x) {
this.stackIn.push(x)
}
pop () {
const stackOutLen = this.stackOut.length
//如果输出栈里有元素 直接弹出
if (stackOutLen) {
return this.stackOut.pop()
}
//如果没有元素 并且输入栈长度不为空 就从输入栈里拿元素放到输出栈里 在弹出
while (this.stackIn.length) {
this.stackOut.push(this.stackIn.pop())
}
return this.stackOut.pop()
}
peek () {
//将x先提出来 然后再放回去
const x = this.pop()
this.stackOut.push(x)
return x
}
empty () {
return !this.stackIn.length && !this.stackOut.length
}
}
225. 用队列实现栈
思路:
队列是先进先出的规则,把一个队列中的数据导入另一个队列中,数据的顺序并没有变,并没有变成先进后出的顺序。
所以用栈实现队列, 和用队列实现栈的思路还是不一样的,这取决于这两个数据结构的性质。
但是依然还是要用两个队列来模拟栈,只不过没有输入和输出的关系,而是另一个队列完全用来备份的!
代码实现:
class MyStack {
constructor() {
this.queue1 = [];
this.queue2 = [];
}
push (x) {
this.queue1.push(x)
}
pop () {
if (!this.queue1.length) {
[this.queue1, this.queue2] = [this.queue2, this.queue1]
}
while (this.queue1.length > 1) {
this.queue2.push(this.queue1.shift())
}
return this.queue1.shift()
}
top () {
const x = this.pop()
this.queue1.push(x)
return x
}
empty () {
return !this.queue1.length && !this.queue2.length
}
}
//使用一个队列实现
class MyStackOne {
constructor() {
this.queue = []
}
push (x) {
this.queue.push(x)
}
pop () {
let size = this.queue.length
while (size-- > 1) {
//不停地取出队列的第一个元素 然后再插到最后去
this.queue.push(this.queue.shift())
}
return this.queue.shift()
}
top () {
const x = this.pop()
this.queue.push(x)
return x
}
empty () {
return !this.queue.length
}
}
总结:
初见队列和栈 总体来说较容易理解 继续加油!!