当前位置:网站首页>Force buckle: implement a queue with two stacks

Force buckle: implement a queue with two stacks

2022-06-22 03:41:00 Yu who wants to fly

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 )

class CQueue {
    

    Stack<Integer> stack1;
    Stack<Integer> stack2;
    public CQueue(){
    
        stack1 = new Stack<Integer>();
        stack2 = new Stack<Integer>();
    }

    public void appendTail(int value) {
    
        stack1.push(value);
    }

    public int deleteHead() {
    
        if(stack2.isEmpty()){
    
            while (!stack1.isEmpty()){
    
                stack2.push(stack1.pop());
            }
        }
        if(stack2.isEmpty()){
    
            return -1;
        }else {
    
            return stack2.pop();
        }
    }
}

This problem is very clear, using two stacks to achieve a queue , Almost the implementation method has been given .

The feature of the stack is first in, then out , The characteristics of queues are first in, first out .

Very clear , It only needs to be put into the stack twice , First in, then out , First in, then out , The natural result is first in, first out , Same as the result of the queue .

Others are questions of logical judgment .

原网站

版权声明
本文为[Yu who wants to fly]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220329265156.html