day10-堆和栈

leetcode 232 栈实现队列

class MyQueue {

    private Stack stack1;
    private Stack stack2;

    private int size;

    public MyQueue() {

        stack1 = new Stack();
        stack2 = new Stack();
    }

    public void push(int x) {
        stack1.push(x);
    }

    public int pop() {
        if(stack2.isEmpty()) {
            int tmp = stack1.size();
            for (int i = 0; i < tmp; i++) {
                stack2.push(stack1.pop());
            }
        }
        return (int)stack2.pop();
    }

    public int peek() {
        if(stack2.isEmpty()) {
            int tmp = stack1.size();
            for (int i = 0; i < tmp; i++) {
                stack2.push(stack1.pop());
            }
        }
        return (int)stack2.peek();
    }

    public boolean empty() {

        if(stack2.isEmpty()){
            int tmp = stack1.size();
            for (int i = 0; i < tmp; i++) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.isEmpty();
    }
}

leetcoce 225 队列实现栈

class MyStack {

    /*private Queue que1;
    private Queue que2;

    public MyStack() {
        que1= new LinkedList();
        que2= new LinkedList();
    }

    public void push(int x) {
        que1.add(x);
    }

    public int pop() {
        int tmp = que1.size();
        for(int i=0;i< tmp-1;i++){
             que2.add(que1.poll());
        }
        int result = (int) que1.poll();

        int tmp2= que2.size();
        for(int j=0;j< tmp2;j++){
            que1.add(que2.poll());
        }
        return result;
    }

    public int top() {
        int tmp = que1.size();
        for(int i=0;i< tmp-1;i++){
            que2.add(que1.poll());
        }
        int result = (int) que1.poll();

        int tmp2= que2.size();
        for(int j=0;j< tmp2;j++){
            que1.add(que2.poll());
        }

        que1.add(result);
        return result;
    }

    public boolean empty() {
        return que1.isEmpty();
    }*/


    // 一个队列也可以实现
    private Queue<Integer> que1;

    public MyStack() {
        que1= new LinkedList();
    }

    public void push(int x) {
        que1.offer(x);
        int tmp = que1.size();
        for(int i=0;i< tmp-1;i++){
            que1.offer(que1.poll());
        }
    }

    public int pop() {
        return que1.poll();
    }

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

    public boolean empty() {
        return que1.isEmpty();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值