using two stacks to simulate a queue


  • 0
    F
    private LinkedList<Integer> stack1;
        private LinkedList<Integer> stack2;
    
        public MyQueue() {
            stack1 = new LinkedList<>();
            stack2 = new LinkedList<>();
        }
    
        public void push(int x) {
            stack1.addLast(x);
        }
    
        public void pop() {
            if (!empty()) {
                while (stack1.size() != 1) {
                    stack2.addLast(stack1.removeLast());
                }
                stack1.clear();
                while (!stack2.isEmpty()) {
                    stack1.addLast(stack2.removeLast());
                }
            }
        }
    
        public int peek() {
            if (!empty()) {
                while (stack1.size() != 1) {
                    stack2.addLast(stack1.removeLast());
                }
                int result = stack1.getLast();
                if (!stack2.isEmpty()) {
                    stack1.addLast(stack2.removeLast());
                }
                return result;
            } else {
                throw new RuntimeException();
            }
        }
    
        public boolean empty() {
            return stack1.isEmpty();
        }
    

Log in to reply
 

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