232. 用栈实现队列
思路:栈具有先进后出的特点,而队列具有先进先出的特点,因此需要用两个栈来实现队列的功能,分别为stackIn和stackOut,当往队列中添加元素时,直接向stackIn中添加元素,当需要队列输出元素时,由于需要输出的元素再stackIn的底部,因此将stackIn中的所有元素输出到stackOut中,此时stackOut最外侧的元素即为需要输出的元素,注意:当stackOut不为空时直接输出,如果stackOut为空,再将stackIn全部输入。peek函数会得到队列的头元素,此时先判断stackOut是否为空,如果为空将stackIn全输入进来,然后将stackOut最外侧的元素返回。
class MyQueue {
public:
stack<int> stackIn;
stack<int> stackOut;
MyQueue() {
}
void push(int x) {
stackIn.push(x);
}
int pop() {
int result;
while(stackOut.empty())
{
while(!stackIn.empty())
{
stackOut.push(stackIn.top());
stackIn.pop();
}
}
result = stackOut.top();
stackOut.pop();
return result;
}
int peek() {
int result = this->pop();
stackOut.push(result);
return result;
}
bool empty() {
if(stackIn.empty()&&stackOut.empty())
{
return true;
}
else
{
return false;
}
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
225. 用队列实现栈
思路:栈先入后出,队列先入先出,因此栈需要输出的元素为队列尾端的元素,因此先获取队列的长度size,然后将队列的前size个元素移出,再加入到队列的尾部,此时需要输出的元素就为队列的头部,输出即可。
class MyStack {
public:
queue<int> q1;
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
int size = q1.size();
size--;
while(size--)
{
q1.push(q1.front());
q1.pop();
}
int result;
result = q1.front();
q1.pop();
return result;
}
int top() {
return q1.back();
}
bool empty() {
return q1.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
收获:
复习了栈和队列内部的函数,以及出入的规则。