• 7 用两个栈实现队列


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

    C++:

     1 class Solution
     2 {
     3 public:
     4     void push(int node) {
     5         stack1.push(node) ;
     6     }
     7 
     8     int pop() {
     9         if (stack2.empty()){
    10             while(!stack1.empty()){
    11                 int t = stack1.top() ;
    12                 stack1.pop() ;
    13                 stack2.push(t) ;
    14             }
    15         }
    16         int res = stack2.top() ;
    17         stack2.pop() ;
    18         return res ;
    19     }
    20 
    21 private:
    22     stack<int> stack1;
    23     stack<int> stack2;
    24 };

    Java:

     1 import java.util.Stack;
     2 
     3 public class Solution {
     4     Stack<Integer> stack1 = new Stack<Integer>();
     5     Stack<Integer> stack2 = new Stack<Integer>();
     6     
     7     public void push(int node) {
     8         stack1.push(node) ;
     9     }
    10     
    11     public int pop() {
    12        if (stack2.empty()){
    13             while(!stack1.empty()){
    14                 stack2.push(stack1.pop()) ;
    15             }
    16         }
    17         int res = stack2.pop() ;
    18         return res ;
    19     }
    20 }
  • 相关阅读:
    nconf修改密码
    快速清空一个文
    freebsd安装snmp
    -bash: mail: command not found
    重置Cacti密码
    cacti添加被监控机全过程
    cacti图形字符乱码
    博客链接
    tar命令详解
    MainPresenter 实现类
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/7898698.html
Copyright © 2020-2023  润新知