首页 > 试题广场 >

用两个栈实现一个队列的功能?

[问答题]
用两个栈实现一个队列的功能?
两个栈stack1,stack2,入队时压入stack1,出队时将stack1中的元素弹出压入stack2中,此时元素恢复原来顺序,将stack2栈顶弹出,完成出队(当stack2不为空时直接弹出stack2栈顶元素)。
  1. class  Solution  
  2. {  
  3. public :  
  4.     void  push( int  node) {  
  5.        stack1.push(node);  
  6.     }  
  7. int  pop() {  
  8.       int  a;  
  9.       if (stack2.empty()){  
  10.           while (!stack1.empty()){  
  11.               a=stack1.top();  
  12.               stack2.push(a);  
  13.               stack1.pop();  
  14.           }  
  15.       }  
  16.       a=stack2.top();  
  17.       stack2.pop();  
  18.       return  a;  
  19.     }  
  20. private :  
  21.     stack<int > stack1;  
  22.     stack<int > stack2;  
  23. };  
编辑于 2017-01-22 16:43:48 回复(0)
 链接:https://www.nowcoder.com/questionTerminal/61e50a60279c48848c06de24325611d1
来源:牛客网
  • class  Solution  
  • {  
  • public :  
  •     void  push( int  node) {  
  •        stack1.push(node);  
  •     }  
  • int  pop() {  
  •       int  a;  
  •       if (stack2.empty()){  
  •           while (!stack1.empty()){  
  •               a=stack1.top();  
  •               stack2.push(a);  
  •               stack1.pop();  
  •           }  
  •       }  
  •       a=stack2.top();  
  •       stack2.pop();  
  •       return  a;  
  •     }  
  • private :  
  •     stack<int > stack1;  
  •     stack<int > stack2;  
  • };  

  • 发表于 2019-03-16 11:19:50 回复(0)