Topic:
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).
test instructions and Analysis: use stack to implement the function of queue. This is the same as stack for the push and enpty operations of the queue. For pop and Peek, because the stack is pop and peek are all from the end of the team, however, the queue is the two operations for the first element of the team. So here we need to use another stack to add a new stack to the current stack in reverse order, take a value for the last element or remove it, and then reverse the new stack back. See the code specifically:
Code:
public class Myqueue {stack<integer> Stack; /** Initialize your data structure here. */Public Myqueue () {stack = new stack<> (); }/** Push element x to the back of the queue. */public void push (int x) {stack.push (x); }/** removes the element from in front of a queue and returns that element. */public int pop () {stack<integer> tempstack=new stack<> (); int lenght=stack.size (); for (int i=0;i<lenght-1;i++) {Tempstack.push (Stack.peek ()); Stack.pop (); } int Res=stack.peek (); Stack.pop (); int tempsize=tempstack.size (); for (int i=0;i<tempsize;i++) {Stack.push (Tempstack.peek ()); Tempstack.pop (); } return res; }/** Get the front element. */public int peek () {stack<integer> tempstack=new stack<> (); int lenght=stack.size (); for (int i=0;i<lenght-1;i++) {Tempstack.push (Stack.peek ()); Stack.pop (); } int Res=stack.peek (); StacK.pop (); Tempstack.push (RES); int tempsize=tempstack.size (); for (int i=0;i<tempsize;i++) {Stack.push (Tempstack.peek ()); Tempstack.pop (); } return res; }/** Returns whether the queue is empty. */public Boolean empty () {return stack.isempty (); }}/** * Your Myqueue object would be instantiated and called as such: * myqueue obj = new Myqueue (); * Obj.push (x); * int param_2 = Obj.pop (); * int param_3 = Obj.peek (); * Boolean param_4 = Obj.empty (); */
[Leetcode] 232. Implement Queue using Stacks Java