- 232.栈实现队列
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
s1.push(x);
}
int pop() {
int x;
if (s2.empty()) {
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
x = s2.top();
s2.pop();
}else {
x = s2.top();
s2.pop();
}
return x;
}
int peek() {
int x;
if (!s2.empty()) {
x = s2.top();
}else {
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
x = s2.top();
}
return x;
}
bool empty() {
if (s1.empty() && s2.empty()) {
return true;
}
return false;
}
private:
stack<int>s1, s2;
};
/**
* 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.队列实现栈
- 容易思维惯性也用两个queue,但其实两个queue也不过是多个副本而已,多此一举,这是由queue的特性决定的
- 主要在pop()的实现上没有想到
- 注意pop与top,pop返回值为void
class MyStack {
public:
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int size = q.size();
while (--size) {
q.push(q.front());
q.pop();
}
// return q.front();
int x = q.front();
q.pop();
return x;
// int x = q.back();
// // q.pop();
// q.
// return x;
}
int top() {
int x = q.back();
return x;
}
bool empty() {
return q.empty();
}
private:
queue<int> q;
};
/**
* 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();
*/