Java beat 93.47%


  • 0
    E

    class MyStack {
    // Push element x onto stack.

    private Queue<Integer> queue;
    public MyStack()
    {
        queue=new LinkedList<Integer>();
    }
    public void push(int x) {
        queue.add(x);
        
    }
    
    // Removes the element on top of the stack.
    public void pop() {
        Queue<Integer> temp=new LinkedList<Integer>();
        int counter=0;
        while(!queue.isEmpty()){
        temp.add(queue.poll());
        counter++;
            
        }
        while(counter>1)
        {
        
            queue.add(temp.poll());
            counter--;
        }
        
        
    }
    
    // Get the top element.
    public int top() {
        Queue<Integer> temp=new LinkedList<Integer>();
        int counter=0;
        while(!queue.isEmpty()){
        temp.add(queue.poll());
        counter++;
            
        }
        while(counter>1)
        {
        
            queue.add(temp.poll());
            counter--;
        }
        int topInteger=temp.poll();
        queue.add(topInteger);
        return topInteger;
        
    }
    
    // Return whether the stack is empty.
    public boolean empty() {
        return queue.isEmpty();
        
    }
    

    }


  • 0
    C

    time: 117 ms


Log in to reply
 

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