Implement Stack using Two Queues

后端 未结 23 765
感情败类
感情败类 2020-11-28 17:05

A similar question was asked earlier there, but the question here is the reverse of it, using two queues as a stack. The question...

Given two queues with their sta

23条回答
  •  死守一世寂寞
    2020-11-28 17:59

    import java.util.LinkedList;
    import java.util.Queue;
    
    class MyStack {
        Queue queue1 = new LinkedList();
        Queue queue2 = new LinkedList();
    
        // Push element x onto stack.
        public void push(int x) {
            if(isEmpty()){
                queue1.offer(x);
            }else{
                if(queue1.size()>0){
                    queue2.offer(x);
                    int size = queue1.size();
                    while(size>0){
                        queue2.offer(queue1.poll());
                        size--;
                    }
                }else if(queue2.size()>0){
                    queue1.offer(x);
                    int size = queue2.size();
                    while(size>0){
                        queue1.offer(queue2.poll());
                        size--;
                    }
                }
            }
        }
    
        // Removes the element on top of the stack.
        public void pop() {
            if(queue1.size()>0){
                queue1.poll();
            }else if(queue2.size()>0){
                queue2.poll();
            }
        }
    
        // Get the top element. You can make it more perfect just example
        public int top() {
           if(queue1.size()>0){
                return queue1.peek();
            }else if(queue2.size()>0){
                return queue2.peek();
            }
            return 0;
        }
    
        // Return whether the stack is empty.
        public boolean isEmpty() {
            return queue1.isEmpty() && queue2.isEmpty();
        }
    }
    

提交回复
热议问题