【剑指offer】栈的压入、弹出序列(java版)

【分析】

问题描述在程序注释中体现,主要思想是:创建一个辅助的堆栈,定义一个指向弹出序列第一位的指针,对于压入序列,每个数压入辅助栈中,每当压入一个数进行判断:栈顶元素与弹出序列指针所指的数进行比较,若相同则弹栈,同时指针后移一位,直到栈顶元素与指针所指元素不同,则压入下一个压入序列中的数。最终若辅助栈为空说明弹出序列为压入序列的弹出顺序。

【代码:链表版】

/*问题:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。
 *例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹
 *出序列。*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution12 {
	public boolean IsPopOrder(ArrayList<Integer> pushA,ArrayList<Integer> popA) {
		if(pushA.size()!=popA.size()){
			return false;
		}
		Stack<Integer> stack = new Stack<Integer>();
		int j=0;
	      for(int i=0;i<pushA.size();i++){
	    	  stack.push(pushA.get(i));
	    	  while((!stack.empty())&&(stack.peek()==popA.get(j))){
	    		  stack.pop();
	    		  j++;
	    	  }
	      }
	      if(stack.empty()){
	    	  return true;
	      }else{
	    	  return false;
	      }
    }
	public static void main(String[] args){
		ArrayList<Integer> pushA = new ArrayList<Integer>();
		pushA.add(1);
		pushA.add(2);
		pushA.add(3);
		pushA.add(4);
		pushA.add(5);
		ArrayList<Integer> popA = new ArrayList<Integer>();
		popA.add(4);
		popA.add(5);
		popA.add(3);
		popA.add(2);
		popA.add(1);
		Solution12 s = new Solution12();
		boolean res = s.IsPopOrder(pushA, popA);
		System.out.println(res);
	}
}

【代码 数组版】

import java.util.ArrayList;
import java.util.Stack;

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
      	if (pushA.length == 0 || popA.length == 0)
			return false;
		if (pushA.length != popA.length) {
			return false;
		}
		Stack<Integer> stack = new Stack<Integer>();
		int j = 0;
		for (int i = 0; i < pushA.length; i++) {
			stack.push(pushA[i]);
			while ((!stack.empty()) && (stack.peek() == popA[j])) {
				stack.pop();
				j++;
			}
		}
		if (stack.empty()) {
			return true;
		} else {
			return false;
		}
    }
}



版权声明:本文为samjustin1原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。