输入样例
8
SHHSSHSS
输出样例
HSHSHSSS
这题用了链队列来写,创建了两条队列
把输入的H全部放进一条队列,输入的S放进一条
循环中通过改变bool的值实现分别输出一次
代码:
#include<iostream>
using namespace std;
typedef char ElemType;
typedef int Status;
#define OK 1
#define ERROR 0
//链队列结构
typedef struct LNode
{
ElemType data;
struct LNode* next;
}LNode, * LinkList;
typedef struct
{
LinkList front;
LinkList rear;
}LinkQueue;
//初始化链队列
bool InitQueue(LinkQueue& Q)
{
Q.front = Q.rear = new LNode;
Q.front->next = NULL;
return OK;
}
//入队
Status EnQueue(LinkQueue& Q, ElemType e)
{
LinkList p = new LNode;
p->next = NULL;
p->data = e;
Q.rear->next = p;
Q.rear = p;
return 1;
}
//出队
Status DeQueue(LinkQueue& Q, ElemType& e)
{
if (Q.front == Q.rear) return ERROR;
LinkList p = Q.front->next;
e = p->data;
Q.front->next = p->next;
delete p;
return 1;
}
int main()
{
int n;
cin >> n;
LinkQueue H; //存放‘H'的链表
LinkQueue S; //存放‘S'的链表
InitQueue(H); //初始化链表
InitQueue(S); //初始化链表
if (n < 2 || n>10)
{
cout << "ERROR";
}
else
{
for (int i = 0; i < n; i++) //入队
{
ElemType e;
cin >> e;
if (e == 'H') EnQueue(H, e);
else if (e == 'S') EnQueue(S, e);
else continue;
}
bool flag = false;
for (int i = 0; i < n; i++)
{
ElemType h;
ElemType s;
if (H.front->next != NULL && flag == false)
{
DeQueue(H, h);
cout << h;
flag = true;
continue;
}
if (S.front->next != NULL && flag == true)
{
DeQueue(S, s);
cout << s;
flag = false;
continue;
}
else if (H.front->next == NULL && flag == false)
{
if (S.front->next != NULL)
{
DeQueue(S, s);
cout << s;
continue;
}
else continue;
}
else if (S.front->next == NULL && flag == true)
{
if (H.front->next != NULL)
{
DeQueue(H, h);
cout << h;
continue;
}
else continue;
}
}
}
}