一、題目描述
題目描述
二脐区、思路
聲明兩個(gè)棧解決:
stack<int> st1用于存儲(chǔ)愈诚;
stack<int> st2用于輔助操作。
push()實(shí)現(xiàn):直接存入st1牛隅;
pop()和peak()實(shí)現(xiàn):先把st1元素依次存入st2炕柔,然后獲取st2的棧頂元素,操作之后將st2的元素又存入st1媒佣。
三匕累、代碼
class MyQueue {
public:
stack<int> st1; // 用于存儲(chǔ)
stack<int> st2; // 用于輔助
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
st1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while(st1.size() != 0){
int cur = st1.top();
st2.push(cur);
st1.pop();
}
int res = st2.top();
st2.pop();
while(st2.size() != 0){
int cur = st2.top();
st1.push(cur);
st2.pop();
}
return res;
}
/** Get the front element. */
int peek() {
while(st1.size() != 0){
int cur = st1.top();
st2.push(cur);
st1.pop();
}
int res = st2.top();
while(st2.size() != 0){
int cur = st2.top();
st1.push(cur);
st2.pop();
}
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
if(st1.size() == 0)
return true;
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();
*/
四、提交結(jié)果
提交結(jié)果