判断出栈序列是否合法

题目描述:1--元素出栈、入栈顺序的合法性。如:入栈的序列(1,2,3,4,5),出栈序列为(4,5,3,2,1),则合法。入栈的序列(1,2,3,4,5),出栈序列为(4,5,2,3,1),则不合法。 

分析如下:

1.如果两个数组长度不相等,直接不合法

2.如果两个数组都为空,合法

3.S用来正常的压栈,q村正确的出栈序列


代码如下:

#include<iostream>
#include<stack>
#include<queue>
using namespace std;
queue<int> StackSort(int* v1,int* v2,int size1,int size2 )//
{
	stack<int> s;
	queue<int> q;
	int i=0;
	int j=0;
	while(i<size1)
	{
		if(v1[i]!=v2[j])
		{
			s.push (v1[i]);
			i++;
		}
		else
		{
			s.push (v1[i]);
			q.push(s.top());
			s.pop();
			i++;
			j++;
		}
	}
	while(!s.empty ())
	{
		q.push(s.top ());
			s.pop();
	}
	return q;

}
bool IsStackSort(int* v1,int* v2,int size1,int size2 )
{
	if(v1==NULL&&v2==NULL)//两个为空
		return true;
	if(size1!=size2)//两个不相等
		return false;
	queue<int> q=StackSort(v1,v2,size1,size2 );
	
    int i=0;
	while(i<size1)
	{
		//cout<<q.front()<<" ";
		if(v2[i]!=q.front ())//判断q和v2是否相同
		{
			return false;
		}
		q.pop();
		i++;
		
	}
	return true;
}
void test1()
{
	int v1[]={1,2,3,4,5};
	int v2[]={4,5,3,2,1};
	int size1=sizeof(v1)/sizeof(v1[0]);
	int size2=sizeof(v2)/sizeof(v2[0]);
	bool l=IsStackSort( v1,v2 ,size1,size2);
	if(l==1)
		cout<<"合法"<<endl;
	else
		cout<<"不合法"<<endl;

	cout<<l<<endl;
}
int main()
{
	test1();
	system("pause");
	return 0;

}


运行结果:





猜你喜欢

转载自blog.csdn.net/wodeqingtian1234/article/details/75635186