面试题9-用两个栈来实现一个队列,完成队列的Push和Pop操作

  • 题目
    • 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
  • 思路:
    • 一个栈压入元素,而另一个栈作为缓冲,将栈1的元素出栈后压入栈2中
  • 代码 
import java.util.Stack;
/**
 *两个栈实现一个队列
 * @author MSI
 */
public class Requeue{
     Stack<Integer> sk1=new Stack<Integer>();
     Stack<Integer> sk2=new Stack<Integer>();
     public void push(int val){
         sk1.push(val);
     }
     public int pop()throws Exception{//将栈1依次出栈,并压入栈2
         if(sk1.isEmpty()&&sk2==null){
             throw new Exception("queue is empty");
         }
         while(sk2.isEmpty()){
             while(!sk1.isEmpty()){
                 sk2.push(sk1.pop());
             }
         }
         return sk2.pop();
     }
    public static void main(String Args[]) throws Exception{
        Requeue q1=new Requeue();
        q1.push(1);
        q1.push(2);
        q1.push(3);
        while(q1!=null)
        System.out.println(q1.pop());       
        }
    }
  • 输出
  • 1
    2
    3
    

      

猜你喜欢

转载自www.cnblogs.com/moonlightml/p/9827555.html