注意点:
1.栈是先进后出,要让栈实现队列,必须要用两个栈
2.peek使用了pop中的函数,所以使用了this->pop(),因为pop是移除第一个元素,但是peek只是返回第一个元素,所以peek要把删除的元素再加回来
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
if(stOut.empty()) {
while(!stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
int peek() {
int res = this->pop();
stOut.push(res);
return res;
}
bool empty() {
return stIn.empty() && stOut.empty();
}
};
/**
* 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();
*/
注意点:
1.使用一个队列便可实现栈,主要就是获得队列的size,将size-1个队列中的数字重新添加到队列中去
2.队列的头是front尾是back
栈的头是top
class MyStack {
public:
queue<int> queue;
MyStack() {
}
void push(int x) {
queue.push(x);
}
int pop() {
int size = queue.size();
size--;
while(size--) {
queue.push(queue.front());
queue.pop();
}
int result = queue.front();
queue.pop();
return result;
}
int top() {
return queue.back();
}
bool empty() {
return queue.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();
*/