https://leetcode.com/problems/implement-queue-using-stacks/description/
Solution 1. Use 1 stack. Recursively push x to the bottom of the stack.
stack<int> st;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
if(st.empty()) {
st.push(x);
return;
}
int y = st.top();
st.pop();
push(x);
st.push(y);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int x = st.top();
st.pop();
return x;
}
/** Get the front element. */
int peek() {
return st.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return st.empty();
}
};
Solution 2. Use 2 stacks for input and output, respectively. move from input to output stack only when output stack is empty.
class MyQueue {
stack<int> sti;
stack<int> sto;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
sti.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
peek();
int x = sto.top();
sto.pop();
return x;
}
/** Get the front element. */
int peek() {
if(sto.empty()) {
while(!sti.empty()) {
sto.push(sti.top());
sti.pop();
}
}
return sto.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return sti.empty() && sto.empty();
}
};
No comments:
Post a Comment