实际上,我们只要把握住栈和队列的特点,就不难做这道题。
栈的特点是先进后出
队列的特点是先进先出
用队列实现栈
首先我们先看队列实现栈,要求实现栈的以下函数:
push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
首先,push()和empty()两个函数是直接调用队列的push()和empty()函数即可,不需要其他操作。
然后是pop()和top()函数,假设在栈中存储了1,2,3,4,5,6 。那么此时栈顶是6,pop掉的数也是6.
但我们现在是把数据存到队列里,如果直接用队列的top()和pop(),那么得到的数是1,pop掉的数也是1。
不难想象,我们需要把队列里的1,2,3,4,5先出队,再进队,此时为6,1,2,3,4,5,此时再使用队列的top()或pop(),就能达到目的。
当然,最后top()得到队列顶的数之后,还需要让6出队,再入队,得到1,2,3,4,5,6原始的队列数据(top()没有改变原始数据)。
class MyStack {
public:
queue<int> q;
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int size = q.size() - 1 ;
for (int i = 0; i < size; i ++)
{
int temp = q.front();
q.pop();
q.push(temp);
}
int temp = q.front();
q.pop();
return temp;
}
/** Get the top element. */
int top() {
int size = q.size()-1;
for(int i = 0; i < size; i++)
{
int temp = q.front();
q.pop();
q.push(temp);
}
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
};
用栈使用队列
需要实现队列的几个函数:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
同上,push()和empty()直接使用栈的对应函数即可。我们也只需要考虑peek()和pop()。
假设现在栈依次存储了1,2,3,4,5,6,队列也依次存储了1,2,3,4,5,6,队列的peek()为1,pop()掉的数据为1,栈的栈顶为6,pop()掉的应该为6。和上面一样,我们可以先定义多一个stack栈s1,从初始数据的栈顶拿数据,得到6,5,4,3,2,1,然后此时使用s1栈的top()得到队列peek()的结果,再从栈s1中取数据存到原始的栈中,恢复原始数据。pop()则是取出6,5,4,3,2,在原始栈中只剩下1的时候使用栈的pop()函数即可。
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
stack<int> s;
/** Push element x to the back of queue. */
void push(int x) {
s.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
stack<int> temp;
while(!s.empty())
{
temp.push(s.top());
s.pop();
}
int res = temp.top();
temp.pop();
while(!temp.empty())
{
s.push(temp.top());
temp.pop();
}
return res;
}
/** Get the front element. */
int peek() {
stack<int> temp;
while(!s.empty())
{
temp.push(s.top());
s.pop();
}
int res = temp.top();
while(!temp.empty())
{
s.push(temp.top());
temp.pop();
}
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return s.empty();
}
};