您的位置:首页 > 运维架构

输入两个整数序列。其中一个序列表示栈的push顺序, 判断另一个序列有没有可能是对应的pop顺序。 为了简单起见,我们假设push序列的任意两个整数都是不相等的

2016-03-01 20:12 1101 查看
比如输入的push序列是1、2、3、4、5,那么4、5、3、2、1就有可能是一个pop系列。

因为可以有如下的push和pop序列:

push 1,push 2,push 3,push 4,pop,push 5,pop,pop,pop,pop,

这样得到的pop序列就是4、5、3、2、1。

但序列4、3、5、1、2就不可能是push序列1、2、3、4、5的pop序列。

代码:

import java.util.LinkedList;

public class Order_Shed {

//思路一

public static boolean judge_is(int[]array1,int[]array2){

if(array1.length==0||array2.length==0||

array1.length!=array2.length)

return false;

int index=0;

LinkedList<Integer> list = new LinkedList<Integer>();

LinkedList<Integer> stack = new LinkedList<Integer>();

for(int i=0;i<array1.length;i++){

if(array1[i]==array2[index]){

list.add(array1[i]);

index++;

while(stack.size()!=0&&stack.get(0)==array2[index]){

list.add(stack.removeFirst());

index++;

}

}else{

stack.addFirst(array1[i]);

}

}

if(stack.size()==0)

return true;

return false;

}

//思路二

public static boolean isPossiPopOrder(int[]array1,int[]array2){

boolean is_possi = false;

if(array1==null||array2==null||

array1.length!=array2.length)

return is_possi;

int index_push = 0;

int index_pop=0;

int length=array1.length;

LinkedList<Integer> list = new LinkedList<Integer>();

while(length>index_pop){

while(list.size()==0||list.getLast()!=array2[index_pop]){

if(index_push>=length)

break;

list.add(array1[index_push]);

index_push++;

}

if(list.getLast()!=array2[index_pop])

break;

list.removeLast();

index_pop++;

}

if(index_pop>=length&&list.size()==0)

is_possi=true;

return is_possi;

}

public static void main(String[] args) {

int[]array1 ={1,2,3,4,5};

int[]array2={4,5,3,2,1};

//测试一

System.out.println(judge_is(array1, array2));

int[]array3 ={4,3,5,1,2};

System.out.println(judge_is(array1, array3));

//测试二

System.out.println(isPossiPopOrder(array1, array2));

System.out.println(isPossiPopOrder(array1, array3));

}

}

结果:

true

false

true

false
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: