Just my java solution.


  • 0
    J
    class MyStack {
       private Queue<Integer> queue;
    	public MyStack(){
    		this.queue = new LinkedList<>();	
    	}
    
         // Push element x onto stack.
        public void push(int x) {
            queue.offer(x);
        }
    
        // Removes the element on top of the stack.
        public void pop() {
        	Queue<Integer> queue1 = new LinkedList<>();
        	int value = 0;
            while(queue.size()>1){
            	value = queue.poll();
            	queue1.offer(value);
            }
          queue.poll();
          queue = queue1;
        }
    
        // Get the top element.
        public int top() {
            Queue<Integer> queue1 = new LinkedList<>(queue);
        	int value = 0;
        	while(!queue1.isEmpty()){
        		value= queue1.poll();
            }
           return  value;
        }
    
        // Return whether the stack is empty.
        public boolean empty() {
            return queue.isEmpty();
        }
        
        public int size(){
        	return queue.size();
        }
    }

Log in to reply
 

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