算法--双栈队列

转载请标明出处http://www.cnblogs.com/haozhengfei/p/98c50d5f654fad63a52f242bb2edb91f.html 


双栈队列练习题

 
双栈队列练习
 

第4节 双栈队列练习题

 

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

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

测试样例:
[1,2,3,0,4,0],6
返回:[1,2]
 
 
1
import java.util.*;
2

3
public class TwoStack {
4
    public int[] twoStack(int[] ope, int n) {
5
        Stack<Integer> stackPush = new Stack<>();
6
        Stack<Integer> stackPop = new Stack<>();
7
        int count = 0; //记录ope中需要弹出的次数
8

9
        for(int tmp: ope){
10
            if(tmp != 0)
11
                stackPush.push(tmp);
12
            else {
13
                count++;//如果是0,表示需要弹出一个元素,记录弹出的次数
14
            }
15
        }
16
        //最后需要返回的result数组中包含的元素的个数就是count的大小
17
        int[] result = new int [count];
18
        //将stackPush中的元素倒入到stackPop,这样在弹出元素的时候就保证了FIFO
19
        while(!stackPush.isEmpty()){
20
            stackPop.push(stackPush.pop());
21
        }
22
        //根据弹出记录的次数放入到result数组中
23
        for(int i=0; i<count; i++){
24
            result[i] = stackPop.pop();
25
        }
26
        return result;
27
    }
28
}
 
 
您的代码已保存
答案正确:恭喜!您提交的程序通过了所有的测试用例
 
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/haozhengfei/p/98c50d5f654fad63a52f242bb2edb91f.html