zoukankan      html  css  js  c++  java
  • 232. Implement Queue using Stacks

    Implement the following operations of a queue using stacks.

    • push(x) -- Push element x to the back of queue.
    • pop() -- Removes the element from in front of queue.
    • peek() -- Get the front element.
    • empty() -- Return whether the queue is empty.

    Notes:

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

     思路:想要使用堆栈实现队列,堆栈出一个再进一个相当于没进没出,所以我们采用两个堆栈实现队列,先进第一个堆栈,再把第一个堆栈的元素依次给另外一个堆栈,那么即将要进来的元素就到了第一个堆栈的栈底,刚好,再从堆栈2到堆栈1,和队列的顺序就保持一致了。

    public class MyQueue {    Stack<Integer>stack1=new Stack<>();    Stack<Integer>stack2=new Stack<>    /** Initialize your data structure here. */

        public MyQueue() {
            
        }
        
        /** Push element x to the back of queue. */
        public void push(int x) {
            while(!stack1.isEmpty())
            {
            	stack2.push(stack1.pop());//堆栈1的元素依次给堆栈2
            }
            stack1.push(x);//x就成了1的栈底元素
    while(!stack2.isEmpty()) { stack1.push(stack2.pop());//再把2给1 } } /** Removes the element from in front of queue and returns that element. */ public int pop() { return stack1.pop();//栈顶元素就是队列的第一个元素 } /** Get the front element. */ public int peek() { return stack1.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return stack1.isEmpty(); } }

      堆栈和队列之间的转换和巧妙,大家可以尝试一下!

  • 相关阅读:
    随机生成字符串,可用来当id
    自己总结的关于uniapp项目用androidstuido打包成apk
    css3 滑动效果 门
    在数组里面随机获取随机的几个内容
    把一个数组分割成两个(不管奇数还是偶数)
    Mysql常用命令
    怎样才能彻底地删除多余输入法软件
    启动MySQL服务
    linux监控命令全覆盖
    浅谈MVC模式与SSH框架
  • 原文地址:https://www.cnblogs.com/zhangfanxmian/p/6929970.html
Copyright © 2011-2022 走看看