剑指offer 用两个栈实现队列 图解栈和队列的转换过程【简单易懂,代码可以直接运行】
栈和队列是两种常见的数据结构。栈的特点是先进后出,就像是压弹夹一样,最先压进去的子弹最后才能发出来。队列的特点的是先进先出,这个十分贴切实际生活,就像是排队一样,排在前面的人才能更快买到饭,排在后面的人需要等待前面的人买过饭之后才能轮到他。
题目描述:
请用栈实现一个队列,支持如下四种操作:
push(x) – 将元素x插到队尾;
pop() – 将队首的元素弹出,并返回该元素;
peek() – 返回队首元素;
empty() – 返回队列是否为空;
注意:
你只能使用栈的标准操作:push to top,peek/pop from top, size 和 is empty;
如果你选择的编程语言没有栈的标准库,你可以使用list或者deque等模拟栈的操作;
输入数据保证合法,例如,在队列为空时,不会进行pop或者peek等操作;
这里面用到栈的内置函数有:
top函数:用来返回出来栈顶元素
pop函数:用来将栈顶元素出栈,返回值是栈顶元素
push函数,将元素压入栈中
都是数据结构中栈的基本操作,基本上数据结构实验上老师都让我们们手动实现过这些内置函数德原理代码。
点个👍吧,秋梨膏!!!
图解如下:
可以将S2理解为工具人,hh
代码如下:
class MyQueue {
public:
stack<int> s1,s2;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while(s1.size() > 1)
{
s2.push(s1.top());
s1.pop();
}
int res = 0;
res = s1.top();
s1.pop();
while(s2.size())
{
s1.push(s2.top());
s2.pop();
}
return res;
}
/** Get the front element. */
int peek() {
while(s1.size() > 1)
{
s2.push(s1.top());
s1.pop();
}
int res = s1.top();
while(s2.size())
{
s1.push(s2.top());
s2.pop();
}
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
s1.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/
点个👍吧,秋梨膏!!