剑指——栈的压入、弹出序列

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

思路:定义一个协助栈stack 先往stack中放入push序列中的值,并将stack的栈顶与pop序列中的值进行比较,一定要先比较不相等的情况,如果不相等则继续往栈中压入值,直到相等或者push序列中的值全部压入栈。接下来判断stack栈顶与pop是否相等,相等的话stack弹出,pop后移,并一定要continue 跳过下面的判断 再次循环。如果在push压尽的情况下不相等,则直接返回false,最后如果正常退出while循环,则判断栈中是否有值,如果有值则可能是pop中缺少数据了,返回false,否则返回true

#include <stdio.h>
#include <iostream>
#include <stack>
#include <vector>
using namespace std;

bool IsPopOrder(vector<int>& vPush, vector<int>& vPop)
{
	if (vPush.size() <= 0 || vPop.size() <= 0)
		return false;
	stack<int> stack;
	auto pushPoint_Begin = vPush.begin(); //定义一个Push迭代器 0
	auto popPoint_Begin = vPop.begin();  //定义一个Pop迭代器  100

	stack.push(*pushPoint_Begin); //先放入stack一个值
	++pushPoint_Begin;

	while (popPoint_Begin!=vPop.end()) //循环终止条件为pop达到end
	{			
		if (stack.top() != *popPoint_Begin)  //不相等
		{
			while ((stack.top() != *popPoint_Begin) && (pushPoint_Begin != vPush.end()))
			{
				stack.push(*pushPoint_Begin);  //不相等的话继续压栈直到相等 或者push中数据压尽
				++pushPoint_Begin;
			}
		}
		if (stack.top() == *popPoint_Begin) //栈顶与序列指针所在值相等
		{
			stack.pop(); //相等的话将栈弹出 
			++popPoint_Begin;  //pop后移	
			continue;
		}
		return false;  //如果push序列中的数据都已经压入栈后 仍然没有与之相等的pop则直接返回false
	}

	if (stack.empty())  //判断栈中是否有数据 
	{
		return true;
	}
	else
		return false;
}

int main(int argc,char *argv[])
{
	vector<int> vPush= { 1,2,3,4,5 };
	vector<int> vPop = { 4,5,3,2,1};

	if (IsPopOrder(vPush, vPop))
	{
		cout << "含有" << endl;
	}
	else
		cout << "不含有" << endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/SwordArcher/article/details/79935472