classMyQueue{ private Stack<Integer> inputStack; private Stack<Integer> outputStack; /** Initialize your data structure here. */ publicMyQueue(){ inputStack = new Stack<>(); outputStack = new Stack<>(); } /** Push element x to the back of queue. */ publicvoidpush(int x){ inputStack.push(x); } /** Removes the element from in front of queue and returns that element. */ publicintpop(){ if(outputStack.empty()) { while(!inputStack.empty()) { outputStack.push(inputStack.pop()); } } return outputStack.pop(); } /** Get the front element. */ publicintpeek(){ if(outputStack.empty()) { while(!inputStack.empty()) { outputStack.push(inputStack.pop()); } } return outputStack.peek(); } /** Returns whether the queue is empty. */ publicbooleanempty(){ return inputStack.empty() && outputStack.empty(); } }
/** Initialize your data structure here. */ publicMyStack(){ in = new LinkedList<>(); out = new LinkedList<>(); } /** Push element x onto stack. */ publicvoidpush(int x){ in.offer(x); while(!out.isEmpty()) { in.offer(out.poll()); } Queue temp =in; in = out; out = temp; } /** Removes the element on top of the stack and returns that element. */ publicintpop(){ return out.poll(); } /** Get the top element. */ publicinttop(){ return out.peek(); } /** Returns whether the stack is empty. */ publicbooleanempty(){ return out.isEmpty(); } }