练习5--用两个栈实现队列

题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:1)所有进栈操作都在stack1进行;
2)出栈,首先将stack1全部压入stack2,Stack2进行出栈;
3)出栈完成后,将stack2全部压入stack1,进行下一次操作。
4)思路参考http://blog.csdn.net/qq_23217629/article/details/51723295
源码:

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

       public void push(int node) {
         stack1.push(new  Integer(node));
     }

      public int pop() {
              int pop;
             while(!stack1.isEmpty()){
                 stack2.push(stack1.pop());
             }
              pop=stack2.pop().intValue();
              while(!stack2.isEmpty()){
                  stack1.push(stack2.pop());
              }
              return pop;
          }  
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容