Using two stack maintain the queue(JAVA)


  • 0
    class MyQueue {
        
        private Stack<Integer> in = new Stack<Integer>();
        private Stack<Integer> out = new Stack<Integer>();
        
        // Push element x to the back of queue.
        public void push(int x) {
            in.push(x);
        }
    
        // Removes the element from in front of queue.
        public void pop() {
            if(out.size() > 0) {
                out.pop();
            }
            else {
                inToOut();
                out.pop();
            }
        }
    
        // Get the front element.
        public int peek() {
            if(out.size() > 0) {
                return out.peek();
            }
            else {
                inToOut();
                return out.peek();
            }
        }
    
        // Return whether the queue is empty.
        public boolean empty() {
            if(in.size() == 0 && out.size() == 0) {
                return true;
            }
            else {
                return false;
            }
        }
        
        //put elements in 'in' to 'out', in the reverse order
        private void inToOut() {
            while(in.size() > 0) {
                out.push(in.pop());
            }
        }
        
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.