[LeetCode] Implement Stack using Queues

本文介绍了一种使用队列来实现栈数据结构的方法,并提供了两种不同的实现方案。一种使用两个队列来模拟栈的行为,另一种则仅使用一个队列完成所有操作。这两种方法均能满足栈的基本操作需求,包括push、pop、top和empty等。

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

思路:采用两个队列模拟

时间复杂度:

代码:

class MyStack {
    Queue<Integer> queue1=new LinkedList<Integer>();
    Queue<Integer> queue2=new LinkedList<Integer>();
    int size=0;
    // Push element x onto stack.
    public void push(int x) {
        queue1.offer(x);
        size++;
    }

    // Removes the element on top of the stack.
    public void pop() {
        while(size!=1)
        {
            queue2.offer(queue1.poll());
            size--;
        }
        if(size==1)
        {
            queue1.poll();
            size--;
        }
        while(!queue2.isEmpty())
        {
            push(queue2.poll());
        }
    }

    // Get the top element.
    public int top() {
        int ret=0;
        while(size!=1)
        {
            queue2.offer(queue1.poll());
            size--;
        }
        if(size==1)
        {
            ret=queue1.peek();
            queue2.offer(queue1.poll());
            size--;
        }
        while(!queue2.isEmpty())
        {
            push(queue2.poll());
        }
        return ret;
    }

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

注意  peek后还得再次入队

优化:这里采用的是两个队列,由于队列FIFO,两个队列的使用就相当于在一个队列中开了个口子,从口子中放水,然后再流回去,能否采用一个队列呢?每次出队列就再次压入。

class MyStack {
    Queue<Integer> que=new LinkedList<Integer>();
    int size=0;
    // Push element x onto stack.
    public void push(int x) {
        que.offer(x);
        size++;
    }

    // Removes the element on top of the stack.
    public void pop() {
        int index=size;
        while(index!=1)
        {
            que.offer(que.poll());
            index--;
        }
        if(index==1)
        {
            que.poll();
            index--;
            size--;
        }
    }

    // Get the top element.
    public int top() {
        int ret=0;
        int index=size;
        while(index!=1)
        {
            que.offer(que.poll());
            index--;
        }
        if(index==1)
        {
            ret=que.peek();
            que.offer(que.poll());
        }
        return ret;
    }

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

 

扩展:

 

转载于:https://www.cnblogs.com/maydow/p/4641239.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值