【算法】代码随想录训练营Day10打卡,leetcode232.用栈实现队列 225. 用队列实现栈
232.用栈实现队列
力扣链接:https://leetcode.cn/problems/implement-queue-using-stacks/
这道题就其实算是很简单的题了,首先我们要了解栈和队列的特点和区别
栈:
线性表,特点是后进先出,犹如一个垃圾筐,后面进去的垃圾,总是在表面上。
所以出栈的顺序和入栈的顺序是相反的
队列:
线性表,先进先出,犹如一个管道,先进入队列的总是先出队列
所以这道题我们要用一个反向的来实现一个正向的,从数学的角度来思考,那么就是负负得正,我们用两个栈来相互进出栈,就可以轻松的把进出栈相反的顺序给变为正常的顺序了
解法
/**
* Initialize your data structure here.
*/
var MyQueue = function() {
this.stackIn = [];
this.stackOut = [];
};
/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.stackIn.push(x);
};
/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/
MyQueue.prototype.pop = function() {
const size = this.stackOut.length;
if(size) {
return this.stackOut.pop();
}
while(this.stackIn.length) {
this.stackOut.push(this.stackIn.pop());
}
return this.stackOut.pop();
};
/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function() {
const x = this.pop();
this.stackOut.push(x);
return x;
};
/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return !this.stackIn.length && !this.stackOut.length
};
用队列实现栈
力扣链接:https://leetcode.cn/problems/implement-stack-using-queues/
这道题其实,用一个队列就ok,我们在出栈的时候,一次从队列弹出其中的值,直到最后一个是真的弹出,其他的数值保存,当最后一个值弹出后,再把之前保存的值依次放入队列
解法
// 使用一个队列实现
/**
* Initialize your data structure here.
*/
var MyStack = function() {
this.queue = [];
};
/**
* Push element x onto stack.
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue.push(x);
};
/**
* Removes the element on top of the stack and returns that element.
* @return {number}
*/
MyStack.prototype.pop = function() {
let size = this.queue.length;
while(size-- > 1) {
this.queue.push(this.queue.shift());
}
return this.queue.shift();
};
/**
* Get the top element.
* @return {number}
*/
MyStack.prototype.top = function() {
const x = this.pop();
this.queue.push(x);
return x;
};
/**
* Returns whether the stack is empty.
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return !this.queue.length;
};
今日心得
今日的这两道题主要就是考察你对栈和队列的特性理解度,并不像其他的算法题一般。这道题对于特性理解足够的同学来说可以很快就找到思路。
文章介绍了如何使用栈实现队列以及用队列实现栈的算法,强调理解栈的后进先出(LIFO)和队列的先进先出(FIFO)特性是解决问题的关键。在栈实现队列中,通过两个栈的交互操作达到队列的效果;而在队列实现栈时,利用队列的一次性弹出所有元素再重新入队来模拟栈的出栈操作。

被折叠的 条评论
为什么被折叠?



