题目要求:
思路:先把这列火车当成是一个由‘H’和‘S’所组成的字符串,首先编写算法,能够使所有的’S’都在‘H’前面,代码如下:
#include<stdio.h>
#include<string.h>
#define ElemType char
#define MaxSize 100
typedef struct{
ElemType data[MaxSize];
int top;
}Stack;
void InitStack(Stack &S)
{
memset(S.data,'\0',MaxSize);
S.top=0;
}
bool Push(ElemType e,Stack &S)
{
if(S.top==(MaxSize-1))return false;
S.data[S.top]=e;
S.top++;
return true;
}
bool Pop(Stack &S,ElemType &e)
{
if(S.top==0)return false;
e=S.data[--S.top];
return true;
}
bool isEmpty(Stack &S)
{
if(S.top==0)return true;
else return false;
}
void Deal(char s[],int n)
{
Stack S;
InitStack(S);
printf("\n输出调度后的车厢排布:\n");
for(int i=0;i<n;i++)
{
if(s[i]=='H')
{
Push(s[i],S);
}
else if(s[i]=='S')
{
printf("S");
}
}
while(!isEmpty(S))
{
ElemType e;
Pop(S,e);
printf("%c",e);
}
printf("\n");
}
int main()
{
char s[100];
printf("\n输入这列火车的排布情况:\n");
scanf("%s",s);
Deal(s,strlen(s));
return 0;
}
运行结果:
刚刚看了王道的讲解视频,发现他们的思路与我的完全相同。