zoukankan      html  css  js  c++  java
  • 40. Implement Queue by Two Stacks【medium】

    As the title described, you should only use two stacks to implement a queue's actions.

    The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.

    Both pop and top methods should return the value of first element.

     
    Example
    push(1)
    pop()     // return 1
    push(2)
    push(3)
    top()     // return 2
    pop()     // return 2
    
    Challenge

    implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE.

    解法一:

     1 class MyQueue {
     2 public:
     3     stack<int> stack1;
     4     stack<int> stack2;
     5 
     6     MyQueue() {
     7     }
     8 
     9     void push(int element) {
    10         stack1.push(element);
    11     }
    12     
    13     void adjust() {
    14         if (stack2.empty()) {
    15             while (!stack1.empty()) {
    16                 stack2.push(stack1.top());
    17                 stack1.pop();
    18             }
    19         }
    20     }
    21     
    22     int pop() {
    23         adjust();
    24         int temp = stack2.top();
    25         stack2.pop();
    26         return temp;
    27     }
    28 
    29     int top() {
    30         adjust();
    31         return stack2.top();
    32     }
    33 };
  • 相关阅读:
    HIFU控制器的显示板
    风扇控制板
    直流源控制板
    HIFU的心脏
    强劲的全桥驱动
    脑电模块
    另一个12导联心电模块
    数据处理,pandas方面遇到的问题
    6.13 django
    python 零基础学习之路-06 常用模块
  • 原文地址:https://www.cnblogs.com/abc-begin/p/8157689.html
Copyright © 2011-2022 走看看