Java solution O(n) top,pop and O(1) push beat 94%


  • 0
    Y
    class MyStack {
        Queue<Integer> q;
        
        public MyStack(){
            q = new LinkedList<Integer>();
            //temp = new LinkedList<Integer>();
        }
        // Push element x onto stack.
        public void push(int x) {
            /*
            final int qSize = q.size();
            q.offer(x);
            for(int i=0; i<qSize; i++){
                q.offer(q.poll());
            }
            */
            q.offer(x);
        }
    
        // Removes the element on top of the stack.
        public int pop() {
            final int qSize = q.size()-1;
            if(qSize <= 0){
                return q.poll();
            }else{
                for(int i=0; i<qSize; i++){
                    q.offer(q.poll());
                }
                return q.poll();   
            }
        }
    
        // Get the top element.
        public int top() {
            final int qSize = q.size()-1;
            if(qSize <= 0){
                return q.peek();
            }else{
                for(int i=0; i<qSize; i++){
                    q.offer(q.poll());
                }
                int front = q.peek();
                q.offer(q.poll());
                return front;
            }
        }
    
        // Return whether the stack is empty.
        public boolean empty() {
            return q.size() == 0;
        }
    }
    

Log in to reply
 

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