栈的push和pop判断

题目:

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

比如输入的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序列。

代码:

注释掉的事开始写的,后来优化了下下~

毕竟双从循环不好看

public class StackJudge {

	public static void Judge(int[] pushSeq, int[] popSeq){
		int[] stack = new int[pushSeq.length];
		int count = pushSeq.length;
		int len = pushSeq.length;
		int push_index = 0;
		int pop_index = 0;
		int stack_tail = -1;
		while(count>0){
			if(push_index<len&&pushSeq[push_index]==popSeq[pop_index]){
				System.out.print(" Push "+pushSeq[push_index]);
				System.out.print(" Pop "+popSeq[pop_index]);
				push_index++;
				pop_index++;
				count--;
			}else if(push_index==len){
				if(stack[stack_tail]==popSeq[pop_index]){
					System.out.print(" Pop "+stack[stack_tail]);
					stack_tail--;
					pop_index++;
					count--;
				}else{
					count=0;
					System.out.println("\nNo");
				}
			}
			else{
				System.out.print(" Push "+pushSeq[push_index]);
				stack[push_index] = pushSeq[push_index];
				push_index++;
				stack_tail++;
			}
//			if(push_index==len){
//				while(count>0){
//					if(stack[stack_tail]==popSeq[pop_index]){
//						System.out.print(" Pop "+stack[stack_tail]);
//						stack_tail--;
//						pop_index++;
//						count--;
//					}else{
//						count=0;
//						System.out.println("\nNo");
//					}
//				}
//			}
		}
	}
	public static void main(String[] args){
		int[] seq1 = {1, 2, 3, 4, 5};
		int[] seq2 = {4 ,5, 3, 2, 1};
		Judge(seq1, seq2);
	}
}

猜你喜欢

转载自to-zoe-yang.iteye.com/blog/1172830