[08] dual-stack queue

topic

A queue is implemented with two stacks. The following statement queue, implement its two functions appendTail and deleteHead, were completed at the end of the queue insert and delete integer integer in the head of the queue function. (If there is no queue element, deleteHead operation returns -1)

Thinking

A push, a pull

reward

The Stack pop java method returns the value of the stack.

Code

class CQueue {
    Stack<Integer> appendTailStack;
    Stack<Integer> deleteHeadStack;
    public CQueue() {

        //负责队末插入的栈
        appendTailStack =new Stack<>();
        //出队的栈
        deleteHeadStack = new Stack<>();
        //平时存放在出队栈中,顺序如同队列
    }

    public void appendTail(int value) {
        if (deleteHeadStack.empty()) appendTailStack.push(value);
        else
            { //先把队push进appendTail栈
            while(!deleteHeadStack.empty()){
                appendTailStack.push(deleteHeadStack.pop());
            }
            //插入
            appendTailStack.push(value);}
        //倒回去
        while(!appendTailStack.empty()){
            deleteHeadStack.push(appendTailStack.pop());
        }
    }

    public int deleteHead() {
        if(deleteHeadStack.empty()) return -1;
        int head = deleteHeadStack.pop();;
        return head;
    }
}

Guess you like

Origin www.cnblogs.com/Jun10ng/p/12345379.html