Title: 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 AR E 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).
Topic Answer:
The requirements of the topic is to use the stack to achieve a queue function, the specific idea is simple, using two stacks to simulate the function of a queue.
The code is as follows:
Class Queue {
Public
Push element x to the back of the queue.
void push (int x) {
S1.push (x);
if (S2.empty ())
{
while (!s1.empty ())
{
S2.push (S1.top ());
S1.pop ();
}
}
}
Removes the element from in front of the queue.
void pop (void) {
if (!s2.empty ())
{
S2.pop ();
}
else if (!s1.empty ())
{
while (!s1.empty ())
{
S2.push (S1.top ());
S1.pop ();
}
S2.pop ();
}
}
Get the front element.
int peek (void) {
if (!s2.empty ())
{
return S2.top ();
}
else if (!s1.empty ())
{
while (!s1.empty ())
{
S2.push (S1.top ());
S1.pop ();
}
return S2.top ();
}
return-1;
}
Return whether the queue is empty.
bool Empty (void) {
if ((S1.empty ()) && (S2.empty ()))
return true;
Else
return false;
}
Private
stack<int> S1;
Stack<int> S2;
};
Leetcode title: Implement Queue using Stacks