第十天| 232.用栈实现队列,225. 用队列实现栈

第十天| 232.用栈实现队列,225. 用队列实现栈

题目关键字:栈、队列

232_题目链接:https://leetcode.cn/problems/implement-queue-using-stacks/description/

代码实现

package LeetCode;

import com.sun.corba.se.spi.ior.ObjectKey;

import java.util.Stack;

public class YangSibo_232 {
    public static void main (String args []) {

    }
}

class MyQueue {
    private  Stack<Integer> stack = new Stack<>();
    private  Stack<Integer> tempstack = new Stack<>();
    public MyQueue() {
    }

    public void push(int x) {
        while (!stack.isEmpty()){
            Integer tempnum = stack.peek();
            stack.pop();
            tempstack.push(tempnum);
        }
        stack.push(x);
        while (!tempstack.isEmpty()){
            Integer tempnum = tempstack.peek();
            tempstack.pop();
            stack.push(tempnum);
        }
    }

    public int pop() {
        return stack.pop();
    }

    public int peek() {
        return stack.peek();
    }

    public boolean empty() {
        if (stack.empty()){
            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();
 */

解题注意事项:

1、stack无法获取长度,只能通过另外一个stack暂存数据
2、pop和push找对一个对上即可,修改另外一个

题目关键字:栈、队列

225_题目链接:https://leetcode.cn/problems/implement-stack-using-queues/

代码实现

package LeetCode;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

public class YangSibo_225 {
    public  static  void main (String args []) {

    }
}
class MyStack {
    Queue<Integer> queue = new LinkedList<>();
    public MyStack() {

    }
    public void push(int x) {
        int circle  = queue.size();
        queue.add(x);
        while (circle > 0) {
            Integer temp = queue.peek();
            queue.poll();
            queue.add(temp);
            circle--;
        }
    }
    public int pop() {
        return queue.poll();
    }

    public int top() {
        return queue.peek();
    }

    public boolean empty() {
        if (queue.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();
 */

解题注意事项:

1、熟悉队列的属性及Queue的实例化方式
2、找出stack和queue的关键差异在数据插入方式以及队列可以获取长度

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值