• 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(); } }

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

  • 相关阅读:
    通过docker把本地AspNetCore WebAPI镜像打包到阿里云镜像仓库并在centos部署
    记一次Java AES 加解密 对应C# AES加解密 的一波三折
    .Net Core MVC实现自己的AllowAnonymous
    Net Core 中间件实现修改Action的接收参数及返回值
    手把手教你实现自己的abp代码生成器
    C# 实现Jwtbearer Authentication
    vs2017调试浏览器闪退
    ABP 邮箱设置
    FastJson反序列化获取不到值
    内网环境下搭建maven私服小技巧
  • 原文地址:https://www.cnblogs.com/zhangfanxmian/p/6929970.html
Copyright © 2020-2023  润新知