美文网首页
代码随想录算法训练营第10天|栈与队列part01

代码随想录算法训练营第10天|栈与队列part01

作者: pangzhaojie | 来源:发表于2023-05-23 09:01 被阅读0次

    栈实现队列

    题目链接

    https://programmercarl.com/0232.%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97.html

    思路

    两个栈,一个入栈,一个出栈

        class MyQueue {
    
    Stack<Integer> stackIn;
    Stack<Integer> stackOut;
    
    public MyQueue() {
        stackIn = new Stack();
        stackOut = new Stack();
    }
    
    public void push(int x) {
        stackIn.push(x);
    }
    
    public int pop() {
        xx();
        return stackOut.pop();
    }
    
    public int peek() {
        xx();
        return stackOut.peek();
    }
    
    public boolean empty() {
        return stackIn.isEmpty() && stackOut.isEmpty();
    }
    
    private void xx() {
        if(stackOut.isEmpty()) {
            while(!stackIn.isEmpty()) {
                stackOut.push(stackIn.pop());
            }
        }
    }
    }
    

    队列实现栈

    题目链接

    https://programmercarl.com/0225.%E7%94%A8%E9%98%9F%E5%88%97%E5%AE%9E%E7%8E%B0%E6%A0%88.html

    思路

        class MyStack {
    
    private Queue<Integer> queue;
    
    public MyStack() {
        queue = new LinkedList();
    }
    
    public void push(int x) {
        queue.add(x);
    }
    
    public int pop() {
        xx();
        return queue.poll();
    }
    
    public int top() {
        xx();
        int a = queue.poll();
        queue.add(a);
        return a;
    }
    
    private void xx() {
        int size = queue.size();
        size--;
        while(size > 0){
            queue.add(queue.poll());
            size--;
        }
    }
    
    public boolean empty() {
        return queue.isEmpty();
    }
    }
    

    相关文章

      网友评论

          本文标题:代码随想录算法训练营第10天|栈与队列part01

          本文链接:https://www.haomeiwen.com/subject/zidtedtx.html