【KOKO-代码随想录算法训练营Day 10| 232|225】

KOKO-代码随想录算法训练营Day 10| 232|225



一、232 用栈实现队列

1.题目

https://leetcode.cn/problems/implement-queue-using-stacks/

2.代码

public class MyQueue232 {
    int size;
    Stack<Integer> stack1;
    Stack<Integer> stack2;
    public MyQueue232() {
        size=0;
        stack1=new Stack<>();
        stack2=new Stack<>();
    }

    public void push(int x) {
        size++;
        if(stack1.isEmpty()){
            stack1.push(x);
            return;
        }
        while (!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
        stack1.push(x);
        while (!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }
    }

    public int pop() {
        if(!stack1.isEmpty()){
            size--;
            return stack1.pop();
        }
        return -1;
    }

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

    public boolean empty() {
        return size==0?true:false;
    }
}

3.总结

用栈实现队列,我是定义了两个栈,在push的时候将栈1中元素弹出压到栈2中,将新加的元素压到栈底,在从栈顶元素拷贝进去。
卡哥是从弹出的时候对栈进行操作的,并且size可以不适用。

二、225. 用队列实现栈

1.题目

https://leetcode.cn/problems/implement-stack-using-queues/

2.代码

class MyStack {
   Queue<Integer> que; //类似于栈
    public MyStack() {
        que=new ArrayDeque();
    }
    public void push(int x) {
        que.add(x);
    }

    public int pop() {
        changeState();
        return que.poll();
    }
    private void changeState() {
        int x=que.size();
        x--;
        while (x-->0){
            que.add(que.poll());
        }
    }

    public int top() {
        int x=pop();
        push(x);
        return x;
    }
  public boolean empty() {
        return que.isEmpty();
    }
}

3.总结

使用队列,只需弹出的时候,将最后一个元素之前的所有元素重新插入队列就可以。
新插入的元素在队列尾部。
令:若用Deque,push,pop()就是对栈进行操作Deque可以当作栈使用。
此题用了Queue去实现。
PS:队列删除从对头删,队尾插入元素。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值