zoukankan      html  css  js  c++  java
  • 用两个栈实现队列功能【剑指offer】

    题目描述:

    用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

    程序代码:

    【方法一】

     1 class Solution
     2 {
     3 public:
     4 
     5     void push(int node) {
     6         stack1.push(node);
     7 
     8 
     9     }
    10 
    11     int pop() {
    12         int a;
    13         if (stack2.size() <= 0){
    14             while (stack1.size()>0){
    15                 a = stack1.top();
    16                 stack2.push(a);
    17                 stack1.pop();
    18             }
    19         }
    20         a = stack2.top();
    21         stack2.pop();
    22 
    23         return a;
    24 
    25 
    26     }
    27 
    28 private:
    29     stack<int> stack1;
    30     stack<int> stack2;
    31 };

    【方法二】

     1 class Solution
     2 {
     3 public:
     4     int cou = 0;
     5     void push(int node) {
     6         stack1.push_back(node);
     7         stack2.push_back(cou++);
     8     }
     9 
    10     int pop() {
    11         int i = 0;
    12         while (stack2[i] == -1)
    13         {
    14             i++;
    15         }
    16         stack2[i] = -1;
    17         return stack1[i];
    18     }
    19 
    20 private:
    21     vector <int> stack1;//存数
    22     vector <int> stack2;//地址
    23 };

    测试用例:

     1 int main()
     2 {
     3     Solution fun;
     4     int a[10] = {1,2,3,0,0,4,0,5,0,0};
     5     int i;
     6     for ( i = 0; i < 10; i++)
     7     {
     8         fun.push(a[i]);
     9     }
    10     for ( i = 0; i < 10; i++)
    11     {
    12         cout << " " << fun.pop() /*<< endl*/;
    13     }
    14     getchar();
    15     return 0;
    16 }
  • 相关阅读:
    【水】希望之花
    如何不用狄利克雷卷积证明莫比乌斯函数性质二
    【数学】gcd
    挂分宝典
    [luogu P6042]「ACOI2020」学园祭 题解
    [luogu P6041]「ACOI2020」布丁暗杀计划 题解
    11.19模拟
    「CSP-S2020」题解
    11.11模拟
    「洛谷P1445」樱花
  • 原文地址:https://www.cnblogs.com/leime/p/9490847.html
Copyright © 2011-2022 走看看