Implement the following operations of a queue using stacks.
- Push (x)--push element x to the back of the queue.
- Pop ()--Removes the element from in front of the queue.
- Peek ()--Get the front element.
- Empty ()--Return whether the queue is empty.
Notes:
- You must use only standard operations of a stack – which means only
push to top
,, peek/pop from top
size
, and is empty
operations is Valid.
- Depending on your language, stack may is not supported natively. You could simulate a stack by using a list or deque (double-ended queue), as long as if you have standard operations of a s Tack.
- You may assume this all operations is valid (for example, no pop or peek operations would be called on an empty queue).
Class Queue {
Public
Push element x to the back of the queue.
void push (int x) {
M_instack.push (x);
}
Removes the element from in front of the queue.
void pop (void) {
if (M_outstack.empty ()) {
if (M_instack.empty ()) {
Return
}
while (!m_instack.empty ()) {
int val = M_instack.top ();
M_instack.pop ();
M_outstack.emplace (Val);
}
}
M_outstack.pop ();
}
Get the front element.
int peek (void) {
if (M_outstack.empty ()) {
if (M_instack.empty ()) {
return-1;
}
while (!m_instack.empty ()) {
int val = M_instack.top ();
M_instack.pop ();
M_outstack.emplace (Val);
}
}
return M_outstack.top ();
}
Return whether the queue is empty.
bool Empty (void) {
Return (M_instack.empty () && m_outstack.empty ());
}
Private
stack<int>m_instack;
stack<int>m_outstack;
};
[Leetcode] 232-implement Queue using Stacks