双栈队列

来源:互联网 发布:ubuntu 图形编程 编辑:程序博客网 时间:2024/03/29 17:20

编写一个类,只能用两个栈结构实现队列,支持队列的基本操作(push,pop)。

给定一个操作序列ope及它的长度n,其中元素为正数代表push操作,为0代表pop操作,保证操作序列合法且一定含pop操作,请返回pop的结果序列。

测试样例:

[1,2,3,0,4,0],6

返回:[1,2]

题目意思是说数组里面有几个0就要出栈几次,所以先将所有元素压栈到stack1中,然后在压栈的过程中判断0的个数然后将stack1中的元素依次放入到栈2中,然后根据0的个数出栈几个;

代码如下:

public int[] twoStack(int[] ope, int n) {        // write code hereStack<Integer> stack1 =new Stack<Integer>();Stack<Integer> stack2 =new Stack<Integer>();        int count=0;for (int i = 0; i < ope.length; i++) {   if(ope[i]!=0){   stack1.push(ope[i]);   }else{   count++;   }}while(!stack1.isEmpty()){  stack2.push(stack1.pop());}        int[] aa =new int[count];        for(int i=0;i<count;i++){         aa[i]=stack2.pop();        }        return aa;}



0 0
原创粉丝点击