【用队列实现栈】【用栈实现队列】Leetcode 232 225

4 篇文章 0 订阅
2 篇文章 0 订阅

【用队列实现栈】【用栈实现队列】Leetcode 232 225

---------------🎈🎈题目链接 用队列实现栈🎈🎈-------------------
---------------🎈🎈题目链接 用栈实现队列🎈🎈-------------------

在这里插入图片描述
在这里插入图片描述

队列的相关操作

创建队列
Queue<Integer> myqueue = new LinkedList<>();
添加元素
myqueue.add();
队列最初的元素
myqueue.peek();
队列弹出元素:
myqueue.poll();
队列大小
myqueue.size();
队列是否为空
myqueue.isEmpty();

栈的相关操作

创建栈
Stack<Integer> mystack = new Stack<>();
添加元素
mystack.push();
栈顶元素
mystack.peek();
弹出栈顶元素:
mystack.pop();
栈大小
mystack.size();
栈是否为空
mystack.isEmpty();

用队列实现栈

class MyStack {
    Queue<Integer> myqueue;

    public MyStack() {
        myqueue = new LinkedList<>();
    }
    
    public void push(int x) {
        myqueue.add(x);
    }
    
    public int pop() {
        for(int i = 0; i < myqueue.size()-1; i++){
            myqueue.add(myqueue.poll());
        }
        return myqueue.poll();
    }
    
    public int peek() {
        int top;
        for(int i = 0; i < myqueue.size()-1; i++){
            myqueue.add(myqueue.poll());
        }
        top = myqueue.peek();
        myqueue.add(myqueue.poll());
        return top;
    }
    
    public boolean empty() {
        if(myqueue.isEmpty()){
            return true;
        }
        else return false;
    }
}

/**
 * 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();
 */

           
    

用栈实现队列

class MyQueue {

    Stack<Integer> mystackin;
    Stack<Integer> mystackout;

    public MyQueue() {
        mystackin = new Stack<>();
        mystackout = new Stack<>();
    }
    
    public void add(int x) {
        while(!mystackout.isEmpty()){
            mystackin.push(mystackout.pop());
        }
        mystackin.push(x);
    }
    
    public int poll() {
        while(!mystackin.isEmpty()){
            mystackout.push(mystackin.pop());
        }
        return mystackout.pop();
    }
    
    public int peek() {
        while(!mystackin.isEmpty()){
            mystackout.push(mystackin.pop());
        }
        return mystackout.peek();

    }
    
    public boolean empty() {
        if(mystackin.isEmpty() && mystackout.isEmpty()){
            return true;
        }
        else return false;

    }
}

/**
 * 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();
 */
  • 11
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值