The sword refers to Offer-Question 9 (Java Edition): Implementing a queue with two stacks

Reference from: "Sword Pointing Offer - Famous Enterprise Interviewer Talking About Typical Programming Questions"

Topic : Implementing a Queue Using Two Stacks Implement a queue
using two stacks. The declaration of the queue is as follows, please implement its two functions appendTail and deleteHead to complete the functions of inserting nodes at the tail of the queue and deleting nodes at the head of the queue respectively.

Main idea : Combine the characteristics of stack FIFO and queue FIFO. Elements are pushed onto the first stack, and then popped onto the second stack, so that the first element inserted is at the top of the second stack. Perform the insert operation on the first stack; perform the delete operation on the second stack, and if the second stack is empty, pop the elements of the first stack to the second stack.

Key Point : Characteristics of Stacks and Queues

Time complexity : insert operation O(1); delete operation O(n)

public class SimulateQueue
{
    private Stack<Integer> inputStack = new Stack<>(); //输入栈
    private Stack<Integer> outputStack = new Stack<>(); //输出栈

    public static void main(String[] args)
    {
        SimulateQueue simulateQueue = new SimulateQueue();
        simulateQueue.appendTail(1);
        simulateQueue.appendTail(2);
        simulateQueue.appendTail(3);
        while (!simulateQueue.isEmpty())
        {
            System.out.println(simulateQueue.deleteHead());
        }
    }

    public boolean isEmpty()
    {
        return inputStack.isEmpty() && outputStack.isEmpty();
    }

    public void appendTail(int node)
    {
        inputStack.push(node);
    }

    public int deleteHead()
    {
        //输出栈为空,则把输入栈的元素弹出到输出栈
        if (outputStack.isEmpty())
        {
            while (!inputStack.isEmpty())
            {
                outputStack.push(inputStack.pop());
            }
        }
        if (outputStack.isEmpty())
        {
            return -1;
        }
        return outputStack.pop();
    }
}

Guess you like

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