● 232.用栈实现队列
个人心得:用两个栈去模拟一个队列,关键是栈元素出来的部分
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 daan=this->pop();
stout.push(daan);
return daan;
}
bool empty() {
return stin.empty()&&stout.empty();
}
};
225.用队列实现栈
用一个队列就可以实现一个栈的功能
class MyStack {
public:
queue<int> que;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int size = que.size();
size--;
while (size--) { // 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
que.push(que.front());
que.pop();
}
int result = que.front(); // 此时弹出的元素顺序就是栈的顺序了
que.pop();
return result;
}
/** Get the top element. */
int top() {
return que.back();
}
/** Returns whether the stack is empty. */
bool empty() {
return que.empty();
}
};