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).
Subscribe to see which companies asked this question
1 classMyqueue {2stack<integer> S1 =NewStack<integer>();3stack<integer> s2 =NewStack<integer>();4 //Push element x to the back of the queue.5 Public voidPushintx) {6 S1.push (x);7 }8 9 //Removes the element from in front of the queue.Ten Public voidpop () { One if(!s2.isempty ()) S2.pop (); A Else{ - while(!s1.isempty ()) S2.push (S1.pop ()); - S2.pop (); the } - } - - //Get the front element. + Public intPeek () { - if(!s2.isempty ())returnS2.peek (); + Else{ A while(!s1.isempty ()) S2.push (S1.pop ()); at returnS2.peek (); - } - } - - //Return Whether the queue is empty. - Public Booleanempty () { in returnS1.isempty () &&s2.isempty (); - } to}
232. Implement Queue using Stacks Java Solutions