1 #include <bits/stdc++.h> 2 using namespace std; 3 4 class myQueue{ 5 private: 6 stack<int> s1, s2; 7 8 public: 9 void add(int x){ 10 s1.push(x); 11 } 12 13 void poll(){ 14 if(s2.empty()){ 15 while(s1.empty() == false){ 16 s2.push(s1.top()); 17 s1.pop(); 18 } 19 } 20 s2.pop(); 21 } 22 23 int peek(){ 24 if(s2.empty()){ 25 while(s1.empty() == false){ 26 s2.push(s1.top()); 27 s1.pop(); 28 } 29 } 30 return s2.top(); 31 } 32 }; 33 34 int main(){ 35 int n; 36 cin>>n; 37 myQueue mq; 38 while(n>0){ 39 --n; 40 string op=""; 41 cin>>op; 42 if(op == "add"){ 43 int temp; 44 cin>>temp; 45 mq.add(temp); 46 } 47 else if(op == "poll"){ 48 mq.poll(); 49 } 50 else 51 cout<<mq.peek()<<endl; 52 } 53 }
两个栈,一个做队尾进队,一个做队头出队。只有当队头栈没有元素时,才把队尾栈元素装过来
 
                    
                 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号