leetcode第225题:Implement Stacks using Queues

Problem

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.

Notes:

  • You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

题目

使用队列实现栈的如下操作。

  • push(x)——把元素x到堆栈。
  • pop()——删除元素堆栈的顶部。
  • top()——获得顶级元素。
  • empty()——返回栈是否为空。

注意

  • 必须只使用队列的标准操作——这意味着只有下面操作是有效的:push队尾,peek/pop对首,size(),是否为空。
  • 根据所用编程语言,只要你只使用队列的标准操作,即使本机不支持队列,也可以通过链表或者双端队列来模拟。
  • 假设所有的操作是有效的(比如空栈中没有pop和top操作)。

题解

解题思路

题目的要求是使用队列来实现栈 ,有两种思路可以解决

  • 一种是使用队首作为栈顶
  • 一种是使用队尾作为栈顶

两种思路应该都可以实现,一种是入栈操作会多一些,一种是出栈操作会多一些。这个题目四个函数中两个都是和栈顶元素的操作有关,因此选择用队首作为栈顶。

代码

/**
 * 使用队列来实现栈。
 * <p>使用队列的队首来当做栈顶。
 * @author zhao
 *
 * @param <E>
 */
public class _225_Implement_Stacks_using_Queues {


    Queue<Integer> q = new LinkedList<Integer>();


    // Push element x onto stack.
    public void push(int x) { 
        q.add(x);   

        int n = q.size();
        while (n > 1) {
            n--;
            q.add(q.poll());
        }
    }

    // Removes the element on top of the stack.
    public void pop() {

        q.poll();
    }

    // Get the top element.
    public int top() {

        return q.peek();
    }

    // Return whether the stack is empty.
    public boolean empty() {

        return q.isEmpty();

    }   
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值