每天一道C语言编程:排队买票
发布人:shili8
发布时间:2025-01-08 13:59
阅读次数:0
**每天一道C语言编程**
### 排队买票####问题描述有n个人要买票,票售卖员只有一张票。每个人都想买票,但只能排成一个队伍。假设每个人在等待的时间内都不会离开队伍。现在,我们需要设计一个算法来让每个人都能买到票。
####问题分析这个问题可以用一个队列来模拟,队列中的元素代表着等待买票的人。我们需要实现一个函数来让每个人都能买到票。
#### 解决方案我们可以使用C语言中的队列数据结构来解决这个问题。具体来说,我们可以使用链式队列(Linked List)来实现这个功能。
c#include <stdio.h>
#include <stdlib.h>
// 定义一个结点的结构体typedef struct Node {
int data;
struct Node* next;
} Node;
// 定义一个队列的结构体typedef struct Queue {
Node* front; // 队头指针 Node* rear; // 队尾指针} Queue;
// 初始化一个空队列void initQueue(Queue* q) {
q->front = NULL;
q->rear = NULL;
}
// 判断队列是否为空int isEmpty(Queue* q) {
return (q->front == NULL);
}
// 入队(添加元素到队尾)
void enqueue(Queue* q, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory error
");
return;
}
newNode->data = data;
newNode->next = NULL;
if (isEmpty(q)) {
q->front = newNode;
q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}
// 出队(删除队头元素)
int dequeue(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty
");
return -1; // 返回-1表示出错 }
Node* temp = q->front;
int data = temp->data;
q->front = temp->next;
free(temp);
if (q->front == NULL) {
q->rear = NULL;
}
return data;
}
// 主函数int main() {
Queue queue;
initQueue(&queue);
// 添加元素到队列中 enqueue(&queue,1);
enqueue(&queue,2);
enqueue(&queue,3);
enqueue(&queue,4);
enqueue(&queue,5);
printf("出队结果:");
for (int i =0; i < 5; i++) {
int data = dequeue(&queue);
if (data != -1) {
printf("%d ", data);
}
}
return0;
}
#### 结果在上面的代码中,我们首先定义了一个结点的结构体和队列的结构体。然后我们实现了几个函数来操作队列,包括初始化队列、判断队列是否为空、入队和出队。
最后,在主函数中,我们创建了一个空队列,然后添加了5个元素到队列中。接着,我们使用出队函数取出每个元素,并打印出结果。
#### 总结在这个例子中,我们使用C语言中的链式队列来模拟排队买票的场景。我们实现了几个函数来操作队列,包括入队和出队。最后,我们使用这些函数来让每个人都能买到票。
这道题目要求你能够理解队列数据结构的基本概念,并且能够使用C语言中的链式队列来解决问题。

