用两个栈实现队列

来源:互联网 发布:金刚1024控台编程 编辑:程序博客网 时间:2024/06/06 00:54

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

public class Solution9 {    static Stack<Integer> a = new Stack<Integer>();    static Stack<Integer> b = new Stack<Integer>();    public void push(int node){        while (!a.isEmpty()){            a.push(node);        }    }    public int pop(){        while (!a.isEmpty()){            b.push(a.pop());        }        while (!b.isEmpty()){            a.push(b.pop());        }        int c = b.pop();        return c;    } public static void main(String args[]){        int[] arry = {1,2,3,4,5};        System.out.println("输入是:");        for (int j=0;j<arry.length;j++){            System.out.print("\t"+arry[j]);        }        System.out.println("\n输出是:");        for (int i=0;i<arry.length;i++){            b.push(arry[i]);            System.out.print("\t"+b.pop());        }    }}
0 0
原创粉丝点击