栈结构练习

今天从刘汝佳的书上看到一个简单的栈的题目

有n节车厢从A方向驶入车站,按进站顺序编号1~n。现让这些火车按照某种特定的顺序进入B方向的铁轨并驶出车站。为了重组车厢,可以借助中转站C。C是一个可以停放任意多节车厢的车站,但由于末端封顶,驶入C的车厢必须按照相反的顺序驶出C。对于每个车厢,一旦从A移入C,就不能再回到A了;一旦从C移入B,就不能回到C了请编程判断判断:按给定的出站顺序,火车能否出站

用 c++ 的 stl 写的话是这样

#include <cstdio>
#include <stack>

using namespace std;

int main()
{
	int n;
	while (scanf("%d", &n) == 1)
	{
		int *target = new int[n+1];
		for (int i=1; i<=n; i++)
		{
			scanf("%d", &target[i]);
		}
		stack<int> s;
		int a=1, b=1, ok=1;
		while (b < n)
		{
			if (a == target[b])
			{
				a++;
				b++;
			}
			else if ( !s.empty() && s.top()==target[b])
			{
				s.pop();
				b++;
			}
			else if (a < n)
			{
				s.push(a);
				a++;
			}
			else
			{
				ok = 0;
				break;
			}
		}
		delete[] target;
		target = NULL;
		if (ok)
		{
			printf("Yesn");
		}
		else
		{
			printf("Non");
		}
	}
	return 0;
}

输入输出

5
1 2 3 4 5
Yes
5
5 4 1 2 3
No
6
6 5 4 3 2 1
Yes

Leave a Reply

Your email address will not be published. Required fields are marked *