Sword refers to Offer09-using two stacks to achieve queue

Problem Description

Implement a queue with two stacks. The declaration of the queue is as follows. Please implement its two functions appendTail and deleteHead, which respectively complete the functions of inserting integers at the end of the queue and deleting integers at the head of the queue. (If there is no element in the queue, the deleteHead operation returns -1)

Example 1:

输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]

Example 2:

输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]

prompt:

1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用

Problem solving ideas

Maintain two stacks, the first stack supports insert operations, and the second stack supports delete operations.

According to the first-in-last-out feature of the stack, every time we insert an element into the first stack (insert to the top of the stack), the bottom of the first stack is the element that is inserted first and needs to be deleted first, and the top of the stack is The element that was inserted last and needs to be deleted last. In order to maintain the first-in-first-out feature of the queue, we introduce a second stack and use the second stack to maintain the elements to be deleted. When performing the delete operation, we first check whether the second stack is empty. If it is empty, we pop the elements in the first stack one by one and insert them into the second stack, so that the order of the elements in the second stack is the order of the elements to be deleted. When we want to perform the delete operation, we pop directly The element of the second stack can be returned.

Implementation code

class CQueue {
    
    
    //维护两个成员变量s1和s2,其中s1主要支持插入元素,s2支持删除元素
    Stack<Integer> s1;
    Stack<Integer> s2;
    public CQueue() {
    
           //在构造方法中创建对象
        s1=new Stack<>();
        s2=new Stack<>();
    }
    //队尾入队时直接将元素压入栈s1中
    public void appendTail(int value) {
    
    
        s1.push(value);         
    }
    //删除元素时,如果s2中存在元素,那么直接把s2栈顶元素删除即可。
    //如果s2为空,那么需要把s1中的全部元素都出栈压入到s2栈中,此时
    //s2栈中各个元素出栈的顺序其实就是模拟队列中出队的顺序。
    //当然,可能s1本身也为空,所以s2也可能为空,如果为空,返回-1,否则弹出s2栈顶元素
    public int deleteHead() {
    
    
        if(!s2.empty()){
    
    
            return s2.pop();
        }else{
    
    
            while(!s1.empty()){
    
    
                s2.push(s1.pop());
            }
        }
        
        if(s2.empty()){
    
    
            return -1;
        }else{
    
      
            return s2.pop();
        }   
        
    }
}

Guess you like

Origin blog.csdn.net/qq_39736597/article/details/113818000