zoukankan      html  css  js  c++  java
  • 面试题之【用两个栈实现队列】

    题目很简单,与之相似的还有用两个队列实现栈,思路类似都是用一个村一个倒,类似负负得正嘛。

    具体分析一下两个栈实现队列,设这两个分别为s1和s2,我们从入队开始,最开始只要直接压倒s1中,然后出队,此事要先将元素全部弹到出再放到s2中;现在的问题是当两个栈都有东西的时候要怎么处理,其实分析一下我们发现s2中的元素就是最先进的,所以pop只要弹s2就行,同理压栈只要压到s1里面,代码如下:

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<stack>
     4 using namespace std;
     5 const std::string PUSH="PUSH";
     6 const std::string POP="POP";
     7 int main()
     8 {
     9     int n;
    10     while(scanf("%d",&n)==1)
    11     {
    12         std::stack<int> s1;
    13         std::stack<int> s2;
    14         for(int i=0;i<n;i++)
    15         {
    16             std:string a;
    17             int num;
    18             std::cin>>a;
    19             if(a==PUSH)
    20             {
    21                 cin>>num;
    22                 s1.push(num);
    23             }
    24             else
    25             {
    26                 if(!s2.empty())
    27                 {
    28                     printf("%d
    ",s2.top());
    29                     s2.pop();
    30                 }
    31                 else
    32                 {
    33                     while(!s1.empty())
    34                     {
    35                         s2.push(s1.top());
    36                         s1.pop();
    37                     }
    38                     if(!s2.empty())
    39                     {
    40                         printf("%d
    ",s2.top());
    41                         s2.pop();
    42                     }
    43                     else
    44                     {
    45                         printf("-1
    ");
    46                     }
    47                 }
    48             }
    49         }
    50     }
    51     return 0;
    52 }

    如果你觉得内容对你有帮助,请点个赞

    知识共享许可协议
    本作品采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可。
  • 相关阅读:
    Leetcode86.分隔链表
    Leetcode39.组合总和
    Leetcode31.下一个排列
    剑指Offer35.复杂链表复制
    剑指Offer14-I.剪绳子
    剑指Offer38.字符串的排序
    Leetcode29.两数相除
    232. Implement Queue using Stacks
    程序员跳槽指南
    226. Invert Binary Tree
  • 原文地址:https://www.cnblogs.com/MrLJC/p/3646412.html
Copyright © 2011-2022 走看看