"Sword Pointing Offer" Java Language - Implementing Queue with Two Stacks

Topic description

Use two stacks to implement a queue to complete the Push and Pop operations of the queue. The elements in the queue are of type int.

ideas

There are several ideas on this topic. The first is to use the second stack as auxiliary space. When a push operation is performed, it is pushed into the first stack. When the pop operation is performed, the element is popped from the first stack to the second stack, and then an element is popped from the stack. Then push the element to the first stack. The time efficiency is O(N^2). The second idea: the two stacks serve as auxiliary spaces for each other. Push the stack operation to the first stack, and then pop the stack, if the second stack is empty, pop the elements of the first stack to the second stack. If it is a push operation, put the elements of the second stack into the first, and then push the stack. So the average complexity is O(N)

code

import java.util.Stack;
    public class Solution {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();

      public  void push(int node) {
            if (stack2.empty()) {
                stack1.push(node);
            } else {
                int size = stack2.size();
                for (int i =0; i<size;i++) {
                    stack1.push(stack2.pop());
                }
                stack1.push(node);
            }
        }

        public  int pop() {
            int result = 0;
            if (stack2.empty()) {
                if (stack1.empty()) {
                    return 0;
                } else {
                    int size = stack1.size();
                    for (int i = 0; i <size; i++) {
                        stack2.push(stack1.pop());
                    }
                    result = stack2.pop();
                }
            } else {
                result = stack2.pop();
            }
            return result;
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325640454&siteId=291194637