LeetCode Implement Stack using Queues

原题链接在这里:https://leetcode.com/problems/implement-stack-using-queues/

本题与Implement Queue using Stacks相对应。

Method 1: 用两个queue来实现stack,push(x) 时,x先放到queue2,在把queue1逐个接到queue2上,再把queue1和queue2互换即可。

pop()时直接poll出来queue1的第一个元素即可。

top() 与 pop() 类似。

Note: 1. 首先生成queue时注意要使用LinkedList, 不能用PriorityQueue, 因为PriorityQueue自带排序功能。

2. 刚开始写时用了que2.clear(),看似当时que1是空的,互换写起来多一行,直接clear就行,其实这是错的。因为上一行 que1 = que2按照java来说已经把这两个变量指向同一个object,如果使用que2.clear(),说明que2指向的object被清空了,那么这时que1也指向这个object,que1指向的也是个空的object了,就会出错。所以这里必须使用交替。

AC java:

class MyStack {
    private Queue<Integer> que1 = new LinkedList<Integer>();
    private Queue<Integer> que2 = new LinkedList<Integer>();
    
    // Push element x onto stack.
    public void push(int x) {
        que2.offer(x);
        while(!que1.isEmpty()){
            que2.offer(que1.poll());
        }
        Queue temp = que1;
        que1 = que2;
        //que2.clear(); //error
        que2 = temp;
    }
    
    // Removes the element on top of the stack.
    public void pop() {
        que1.poll();
    }

    // Get the top element.
    public int top() {
        return que1.peek();
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return que1.isEmpty();
    }
}

Method 2: 这种想法与Method1很类似,不过这次只用一个queue,push(x)时加到队尾,然后rotate size()-1次即可。

AC Java:

<span style="font-size:14px;">class MyStack {
    private Queue<Integer> que1 = new LinkedList<Integer>();

    // Push element x onto stack.
    public void push(int x) {
        que1.offer(x);
        for(int i = 0; i<que1.size()-1;i++){
            que1.offer(que1.poll());
        }
    }
    
    // Removes the element on top of the stack.
    public void pop() {
        que1.poll();
    }

    // Get the top element.
    public int top() {
        return que1.peek();
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return que1.isEmpty();
    }
}</span>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值