编写一个类,只能用两个栈结构实现队列,支持队列的基本操作(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 here
Stack<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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)