栈的压入、弹出序列


  • 题目描述:

    输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

  • 分析:

    很容易想到,我们需要一个辅助栈来模拟这个入栈出栈的过程。对比入栈序列和出栈序列,如果下一个要出栈的数字正好在栈顶,则直接从栈中弹出。如果不在栈顶,则从入栈序列中还没有入栈的数字开始依次压入栈中,直到找到下一个需要弹出的数字。如果入栈序列都压入栈了仍然没有找到下一个弹出的数字,则该序列不是弹出序列。

    bool IsPopOrder(vector<int> pushV, vector<int> popV) 
    {
    	if (pushV.size() != popV.size() || pushV.size() == 0)
    		return false;
    
    	bool flag = false;
    	stack<int> stack;
    	int indexpush = 0; // 用来指向入栈序列中当前对比的位置
    
    	for (int i = 0; i < popV.size(); ++i)
    	{
    		// 栈空或栈顶元素不是当前要弹出的数字时,入栈序列依次压入辅助栈
    		if (stack.empty() || stack.top() != popV[i])
    		{ 
    			while (indexpush < pushV.size() && pushV[indexpush] != popV[i])
    			{ 
    				stack.push(pushV[indexpush]);
    				++indexpush;
    			}
    			if (indexpush < pushV.size() && pushV[indexpush] == popV[i]) ++indexpush;
    		}
    		else 
    			stack.pop();
    	}
    	// 当入栈序列和出栈序列都被访问完成且辅助栈为空时
    	if (indexpush == pushV.size() && stack.empty())
    		flag = true;
    
    	return flag;
    	
    }
    
原文地址:https://www.cnblogs.com/Bill-LHR/p/6814289.html