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).

    不难,想明白就好,貌似之前看到过这样的题目;一个栈用来存放push的东西,每次需要pop或者peek的时候,再将该栈的所有数据移到另外一个栈里。

     1 class Queue {
     2 public:
     3     stack<int> Squeue1;
     4     stack<int> Squeue2;
     5     // Push element x to the back of queue.
     6     void push(int x) {
     7         Squeue1.push(x);
     8     }
     9 
    10     // Removes the element from in front of queue.
    11     void pop(void) {
    12             
    13             int q;
    14             if(Squeue2.empty()){
    15             while(!Squeue1.empty()){
    16             q=Squeue1.top();
    17             Squeue2.push(q);
    18             Squeue1.pop();
    19             }
    20             }
    21             Squeue2.pop();
    22         }
    23         
    24   
    25 
    26     // Get the front element.
    27     int peek(void) {
    28             int p,q;
    29             if(Squeue2.empty()){
    30             while(!Squeue1.empty()){
    31             q=Squeue1.top();
    32             Squeue2.push(q);
    33             Squeue1.pop();
    34             }
    35             }
    36             p=Squeue2.top();
    37             return p;
    38     }
    39 
    40     // Return whether the queue is empty.
    41     bool empty(void) {
    42         if(Squeue1.empty()&&Squeue2.empty()) return true;
    43         else return false;
    44         
    45     }
    46 };
  • 相关阅读:
    盘古越狱工具在用户空间的行为
    hdu 5538 House Building(长春现场赛——水题)
    html 锚点定位
    OOP版电子词典
    有趣的JavaScript原生数组函数
    &lt;LeetCode OJ&gt; 121. /122. Best Time to Buy and Sell Stock(I / II)
    hadoop 出现FATAL conf.Configuration: error parsing conf file,异常
    IT痴汉的工作现状10-Sprint Planning
    2015 Astar Contest
    无法使用BIPublisher开发报表
  • 原文地址:https://www.cnblogs.com/LUO77/p/4986907.html
Copyright © 2011-2022 走看看