[Sword offer] 08 Realize the queue with two stacks

1. Problem description

1. 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)

Two, the solution

1. A stack is used to store the stack

2. A stack is used to store out of the stack

3, concrete operation

A: Construction method
Initialize stackIn and stackOut to be empty

B: Insert element

Insert element corresponding method appendTail
stackIn directly insert element

C: Delete element

Delete the element corresponding method deleteHead

If stackOut is empty, pop all the elements in stackIn and insert it into stackOut.
If stackOut is still empty, return -1, otherwise pop out an element from stackOut and return

Three, the code

package com.haoxiansheng.demo01.SwordfingerOffer;

import lombok.extern.slf4j.Slf4j;
import java.util.Stack;

/**
 * @author flame
 * @data 2020/10/21
 */
@Slf4j
public class CQueue {
    
    
    private Stack<Integer> stackIn;
    private Stack<Integer> stackOut;

    public CQueue() {
    
    
        stackIn = new Stack<>();
        stackOut = new Stack<>();
    }

    public static void main(String[] args) {
    
    
        CQueue queue = new CQueue();
        queue.appendTail(8);
        queue.appendTail(9);
        queue.appendTail(10);
        log.info("pop=>{}", queue.deleteHead());
        log.info("pop=>{}", queue.deleteHead());
        log.info("pop=>{}", queue.deleteHead());
        log.info("pop=>{}", queue.deleteHead());
    }

    /**
     * 入队
     * @param value
     */
    public void appendTail(int value) {
    
    
        stackIn.push(value);
    }

    /**
     * 出队
     * @return
     */
    public int deleteHead() {
    
    
        if (!stackOut.isEmpty()) {
    
    
            return stackOut.pop();
        } else {
    
    
            while (!stackIn.isEmpty()) {
    
    
                stackOut.push(stackIn.pop());
            }
        }
        return stackOut.isEmpty() ? -1 : stackOut.pop();
    }
}

Guess you like

Origin blog.csdn.net/qq_40996741/article/details/109212296