代码随想录算法训练营第十天【栈与队列】232.用栈实现队列、225.用队列实现栈

232.用栈实现队列

心得:思路不难,栈和队列的特性要掌握

  1)栈,先进后出;队列,先进先出

  2)初始化一个栈,Stack<Integer> stack = new Stack<>()

  3)放入元素,stack.push()

  4)弹出栈顶元素,stack.pop()

  5)获取栈顶元素但不弹出,stack.peek()

  6)判断栈是否为空,stack.isEmpty()

复制代码
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() {
        if(stackOut.isEmpty()){
            while(!stackIn.isEmpty()){
                stackOut.push(stackIn.pop());
            }
        }
        return stackOut.pop();
    }
    
    public int peek() {
        int result = this.pop();
        stackOut.push(result);
        return result;
    }
    
    public boolean empty() {
        return stackIn.isEmpty() && stackOut.isEmpty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */
复制代码

225.用队列实现栈

力扣题目链接

心得:掌握队列的基本方法,关注pop()的实现方式

  1)在队列后面增加x,deque.addLast(x)

  2)获取队列的第一个值,但不弹出,deque.peekFirst()

  3)弹出队列的第一个值,deque.pollFirst()

复制代码
class MyStack {
    Deque<Integer> deque;
    public MyStack() {
        deque = new ArrayDeque<>();
    }
    
    public void push(int x) {
        deque.addLast(x);
    }
    
    public int pop() {
        int move = deque.size()-1;
        while (move-- > 0) {
            deque.addLast(deque.pollFirst());
        }
        return deque.pollFirst();
    }
    
    public int top() {
        return deque.peekLast();
    }
    
    public boolean empty() {
        return deque.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */
复制代码

 

posted @   橙子的房东  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示