双栈队列

来源:互联网 发布:挖矿软件 编辑:程序博客网 时间:2024/04/19 16:15
  • 编写一个类,只能用两个栈结构实现队列,支持队列的基本操作(push,pop)给定一个操作序列ope及它的长度n,
  • 其中元素为正数代表push操作,为0代表pop操作,保证操作序列合法且一定含pop操作,请返回pop的结果序列。

  • 声明StackPush和StackPop,把数据装入StackPush中倒出来再装进StackPop中再倒出来

  • 两个注意的点:
  • 1、如果StackPush要往StackPop中导入数据,那么必须把StackPush中所有的数据一次性倒完
  • 2、如果StackPop中有数据,则不能发生倒数据的行为
public class Main {    public static int[] twoStack(int[] ope, int n) {        if (ope==null || n==0) {            return null;        }        Stack<Integer> stackPush = new Stack<>();        Stack<Integer> stackPop = new Stack<>();        int popCount=0;        for(int i=0;i<n;i++){            if (ope[i]!=0) {                stackPush.push(ope[i]);            }else{                popCount++;            }        }        System.out.println(stackPush);        int result[] = new int[popCount];        while(!stackPush.isEmpty()){            stackPop.push(stackPush.pop());        }            System.out.println(stackPop);        for(int i=0;i<popCount;i++){            result[i]=stackPop.pop();            System.out.println(result[i]);        }        return result;    }    public static void main(String[] args) {        int A[]={1,2,3,0,4,0};        twoStack(A, A.length);    }}
原创粉丝点击