[Jianzhi Offer] 09. Use two stacks to realize the queue

topic description

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

Example 1

enter:

["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]

output:

[null,null,3,-1]

Example 2

enter:

["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]

output:

[null,-1,null,null,5,2]

answer

  • The stack cannot realize the queue function: the element at the bottom of the stack (corresponding to the first element of the queue) cannot be deleted directly, and all the elements above need to be popped out of the stack;
  • The double stack can realize the reverse order of the list: there is a stack A = [1,2,3] with three elements and an empty stack B = []. If the loop executes the A element out of the stack and adds it into the stack B until the stack A is empty, then A = [], B = [3,2,1], that is, the elements of the stack B realize the reverse order of the elements of the stack A.
  • Use stack B to delete the first element of the team: After the reverse order, B executes popping the stack, which is equivalent to deleting the bottom element of A, which corresponds to the first element of the team.
    insert image description here

Code

public class CQueue {
    
    

    final private Stack<Integer> stack1, stack2;

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

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

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

Guess you like

Origin blog.csdn.net/charenCsdn/article/details/123423216