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

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操做。 队列中的元素为int类型。
 
import java.util.Stack;
 
public class Solution {
     Stack<Integer> stack1 = new Stack<Integer>();
     Stack<Integer> stack2 = new Stack<Integer>();
 
     public void push( int node) {
         int temp = 0 ;
         if (stack1.isEmpty()) {
             stack1.push(node);
             return ;
         }
         while (!stack1.isEmpty()){
             temp=stack1.pop();
             stack2.push(temp);
         }
         stack1.push(node);
         while (!stack2.isEmpty()){
             temp = stack2.pop();
             stack1.push(temp);
         }
       
 
     }
 
     public int pop() {
        if (stack1.isEmpty()){
              throw new RuntimeException( "" );
        }
         return stack1.pop();
     }
}
相关文章
相关标签/搜索