one queue is empty, another is full


  • 0
    F
    private LinkedList<Integer> queue1;
        private LinkedList<Integer> queue2;
    
        public MyStack() {
            queue1 = new LinkedList<>();
            queue2 = new LinkedList<>();
        }
    
        public void push(int x) {
            if (queue2.isEmpty()) {
                queue1.addLast(x);
            } else {
                queue2.addLast(x);
            }
        }
    
        public void pop() {
            if (!empty()) {
                if (!queue1.isEmpty()) {
                    while (queue1.size() != 1) {
                        queue2.addLast(queue1.removeFirst());
                    }
                    queue1.clear();
                } else {
                    while (queue2.size() != 1) {
                        queue1.addLast(queue2.removeFirst());
                    }
                    queue2.clear();
                }
            }
        }
    
        public int top() {
            if (!empty()) {
                if (!queue1.isEmpty()) {
                    while (queue1.size() != 1) {
                        queue2.addLast(queue1.removeFirst());
                    }
                    int result = queue1.getFirst();
                    queue2.addLast(queue1.removeFirst());
                    return result;
                } else {
                    while (queue2.size() != 1) {
                        queue1.addLast(queue2.removeFirst());
                    }
                    int result = queue2.getFirst();
                    queue1.addLast(queue2.removeFirst());
                    return result;
                }
            } else {
                throw new RuntimeException();
            }
        }
    
        public boolean empty() {
            return queue1.isEmpty() && queue2.isEmpty();
        }
    

Log in to reply
 

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