当前位置:网站首页>Sword finger offer 09 Implementing queues with two stacks

Sword finger offer 09 Implementing queues with two stacks

2022-07-05 08:21:00 Programmer Xiao Li

Use two stacks to implement a queue . The declaration of the queue is as follows , Please implement its two functions appendTail and deleteHead , The functions of inserting integers at the end of the queue and deleting integers at the head of the queue are respectively completed .( If there are no elements in the queue ,deleteHead  Operation return -1 )

Example 1:

Input :
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
Output :[null,null,3,-1]

Example 2:

Input :
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
Output :[null,-1,null,null,5,2]

Tips :

1 <= values <= 10000
At most  appendTail、deleteHead Conduct  10000  Secondary call

Ideas :

1. An insert stack , An output stack . When inserting data , Write into the insert stack .

2. When outputting data , Pop up from the output stack first , If the output stack does not exist , Then press... From the input stack in turn .

class CQueue {

    Stack<Integer> pushStack = new Stack<Integer>();
    Stack<Integer> popStack = new Stack<Integer>();
    public CQueue() {

    }
    
    public void appendTail(int value) {
        pushStack.push(value);
    }
    
    public int deleteHead() {
        if (popStack.empty()){
            while (!pushStack.empty()){
                popStack.push(pushStack.pop());
            }
        }

        if (popStack.empty()){
            return -1;
        }
        return popStack.pop();
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */

原网站

版权声明
本文为[Programmer Xiao Li]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050816402704.html