设车辆厂生产了硬座车厢和软座车厢共n节(混合在一起),要求使用队列的基本操作,编程实现所有硬座车厢和所有软座车厢交替排列。例如硬座车厢用H来表示,软座车厢用S来表示,从键盘上输入8节车厢代号为SHHSSHSS ,输出为HSHSHSSS。若从键盘输入8节车厢代号为SHHSHHSH ,输出为HSHSHSHH。 输入格式: 第一行输入硬座和软座车厢共有的节数,2<=节数<=10; 第二行按节数输入车厢代号。 输出格式: 若车厢节数超出合法范围,输出“ERROR”,否则输出H和S车厢交替排列结果,注意输出结果以H开头。用C语言编写
时间: 2024-02-22 19:56:22 浏览: 27
以下是使用队列实现所有硬座车厢和所有软座车厢交替排列的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
typedef struct {
char data[MAXSIZE];
int front, rear;
} Queue;
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
int isEmpty(Queue *q) {
return q->front == q->rear;
}
int isFull(Queue *q) {
return (q->rear + 1) % MAXSIZE == q->front;
}
void enQueue(Queue *q, char x) {
if (isFull(q)) {
printf("Queue is full\n");
return;
}
q->data[q->rear] = x;
q->rear = (q->rear + 1) % MAXSIZE;
}
char deQueue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty\n");
return '\0';
}
char x = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return x;
}
int main() {
int n;
char train[MAXSIZE];
scanf("%d", &n);
if (n < 2 || n > 10) {
printf("ERROR\n");
return 0;
}
scanf("%s", train);
Queue h, s;
initQueue(&h);
initQueue(&s);
for (int i = 0; i < n; i++) {
if (train[i] == 'H') {
enQueue(&h, train[i]);
} else if (train[i] == 'S') {
enQueue(&s, train[i]);
} else {
printf("ERROR\n");
return 0;
}
}
printf("H");
while (!isEmpty(&h) || !isEmpty(&s)) {
if (!isEmpty(&h)) {
printf("%c", deQueue(&h));
}
if (!isEmpty(&s)) {
printf("%c", deQueue(&s));
}
}
printf("\n");
return 0;
}
```
输入格式为第一行输入硬座和软座车厢共有的节数,第二行按节数输入车厢代号。输出结果以H开头,若车厢节数超出合法范围,输出“ERROR”。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)