题目很简单,与之相似的还有用两个队列实现栈,思路类似都是用一个村一个倒,类似负负得正嘛。
具体分析一下两个栈实现队列,设这两个分别为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 }