zoukankan      html  css  js  c++  java
  • LeetCode: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 top, peek/pop from top, size, 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).
     
     两个栈实现队列。
     1 class Queue {
     2 private:
     3     stack<int> stack1,stack2;
     4 public:
     5     // Push element x to the back of queue.
     6     void push(int x) {
     7       
     8         stack1.push(x);
     9         
    10     }
    11 
    12     // Removes the element from in front of queue.
    13     void pop(void) {
    14         if(stack2.empty())
    15         {
    16             while(!stack1.empty())
    17             {
    18                 stack2.push(stack1.top());
    19                 stack1.pop();
    20             }
    21         }
    22         stack2.pop();
    23         
    24     }
    25 
    26     // Get the front element.
    27     int peek(void) {
    28         if(stack2.empty())
    29         {
    30             while(!stack1.empty())
    31             {
    32                 stack2.push(stack1.top());
    33                 stack1.pop();
    34             }
    35         }
    36         return stack2.top();
    37         
    38         
    39     }
    40 
    41     // Return whether the queue is empty.
    42     bool empty(void) {
    43         if(stack1.empty()&&stack2.empty())
    44             return true;
    45         else
    46             return false;
    47         
    48     }
    49 };
  • 相关阅读:
    Fetch的使用
    if判断中的true和false
    分布式、微服务和集群的初步了解
    关于视频的知识点
    ajax请求
    jq的遍历关系元素方法集合
    docker安装Mysql
    设计模式系列之七大原则之——开闭原则
    设计模式系列之七大原则之——里式替换原则
    设计模式系列之七大原则之——依赖倒转原则
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4723529.html
Copyright © 2011-2022 走看看