现在的位置: 首页 > 综合 > 正文

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序

2013年12月02日 ⁄ 综合 ⁄ 共 777字 ⁄ 字号 评论关闭

题目描述:

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

poj地址为:http://ac.jobdu.com/problem.php?pid=1366

可以AC的代码:

bool isStackSequence(int *input,int *output,int len)
{
	/*if(input==NULL || output==NULL)
	{
		throw new exception("the input is error");
	}*/
	stack<int> st;
	while(len--)
	{
		st.push(*input++);
		while(!st.empty() && st.top()==*output)
		{
			st.pop();
			output++;
		}
	}
	if(st.empty())
	{
		return true;
	}else
	{
		return false;
	}
}
int main(int argc, const char * argv[])
{
	int n,i;
	//fstream cin("input.txt");
	while(cin>>n)
	{
		int *input=new int[n];
		int *output=new int[n];
		for(i=0;i<n;i++)
		{
			cin>>input[i];
		}
		for(i=0;i<n;i++)
		{
			cin>>output[i];
		}
		if(isStackSequence(input,output,n))
		{
			cout<<"Yes"<<endl;
		}else
		{
			cout<<"No"<<endl;
		}
		delete []input;
		delete []output;
	}
	//getchar();
	return 0;
}

 

抱歉!评论已关闭.