算法与数据结构实验题 3.1 火车

1、题目大意:

★实验任务
TonyY 等火车无聊的时候,会去观察火车的排列,有一天他思考这么一个问 题,火车总站的火车只能进站,要出站的话只能先出最后进站的那辆车,那么知 道火车的进站顺序,能不能把它的出站顺序调整成火车站想要的呢?

★数据输入
输入第一行为一个正整数 n 表示火车辆数(编号 1-n)(1<=n<=9)。 然后为两个长度为 n 的序列,表示火车的进站顺序和出站顺序。每辆火车刚 好进出站各一次。

★数据输出
如果可以调整,输出 Yes 和出入站顺序。 如果不能,输出 No。

输入示例 输出示例
3
123
321
输出示例
Yes
in
in
in
out
out
out

2.主要代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct  astack *Stack;
typedef struct astack
{
	int top;
	int *data;
} Astack;

int StackEmpty(Stack S)
{
	return S->top<0;
}
void Push(int x,Stack S)
{
	S->data[++S->top]=x;

}

int Pop(Stack S)
{
	if(!StackEmpty(S))
	{
		return S->data[S->top--];
	}
}
int main()
{
	Stack S=(Stack)malloc(sizeof*S);
	S->data=(int*)malloc(100*sizeof(int));
	S->top=-1;
	int n;
	char str[100][100];
	scanf("%d",&n);
	char in[100],out[100];
	scanf("%s",in);
	scanf("%s",out);
	int i,j,first=0,k=0;
	for(i=0; i<n; i++)
	{
		Push(in[i]-48,S);
		strcpy(str[k],"in");//进站一个
		k++;
		while(!StackEmpty(S))
		{
			if(S->data[S->top]==out[first]-48)//栈顶元素与出站顺序的第一个相同时,栈顶元素出栈,输出out
			{
				Pop(S);
				strcpy(str[k],"out");
				k++;
				first++;//出站元素变成之前的下一个
			}
			else//栈顶元素与出站第一个不同时,退出循环,继续进栈
			{
				break;
			}
		}
	}
	if(StackEmpty(S))//若此时栈为空,说明车均已出站,输出Yes
	{
		printf("Yes\n");
		for(i=0; i<k; i++)
		{
			printf("%s\n",str[i]);//进出站顺序
		}
	}
	else
	{
		printf("No\n");
	}
	return 0;
}
posted @ 2016-09-25 12:32  laixl  阅读(419)  评论(0编辑  收藏  举报