Jianzhi offer09 uses two stacks to implement the queue

Title address

https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/comments/

Ideas

Use two stacks, because the stack is advanced and out, the queue is opposite, so the elements in the stack should be reversed,
so every time you put element A, first put all the elements in the first stack on the second stack , And then put element A on the first stack, and
finally put all the elements in the second stack on the first stack. In this way, the first stack is the queue. Each time you fetch elements, you can directly pop the stack.

Code

/**
 * @Auther: wwh
 * @Date: 2020-03-13 23:18
 * @Description: 2020年03月13日23:19:02--2020年03月13日23:37:57
 */
public class CQueue {
    private Stack<Integer> stack1 ;
    private Stack<Integer> stack2 ;
    public CQueue() {
        stack1 = new Stack<Integer>();
        stack2 = new Stack<Integer>();
    }

    public void appendTail(int value) {
        if(stack1.empty()){
            stack1.add(value);
        }else {
            while (!stack1.isEmpty()){
                stack2.add(stack1.pop());
            }
            stack1.add(value);
            while (!stack2.isEmpty()){
                stack1.add(stack2.pop());
            }

        }
    }

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


    public static void main(String[] args) {
        CQueue que = new CQueue();
        que.appendTail(1);
        que.appendTail(2);
        que.appendTail(3);
        System.out.println(que.deleteHead());
        System.out.println(que.deleteHead());
        System.out.println(que.deleteHead());

    }
}

postscript

Some people in the comment area suggested using LinkedList to simulate the queue instead of using the original Stack, because Stack inherits the Vector interface, and the bottom layer of Vector is AbstractList, which is an array, then the problem of space expansion must be considered, but the basic idea is the same. The performance has improved a lot.
The inventor of the previous hcaricp invented FastList by himself, because it ensures that it will not cross the border, the rangeCheck of the ArrayList is removed, and the performance is also improved a lot. Underworld is a bit similar, that is to pursue performance as much as possible. TODO find time to study how to implement the code of FastList (the code is said to be very short ...)

Published 33 original articles · praised 37 · 110,000 views

Guess you like

Origin blog.csdn.net/hagle_wang/article/details/104852549