用C语言为冬奥会志愿者建立一个N个志愿者队列编号的顺序表,对表进行插入、删除、查找等操作。分别输出结果。 要求如下: 1)用顺序表来实现。 2)用单链表来实现。
时间: 2024-11-11 07:22:59 浏览: 15
在C语言中,我们可以使用数组(顺序表)或链表(单链表)来为冬奥会志愿者建立队列。这里我会分别介绍这两种方法。
**1. 使用顺序表实现:**
```c
typedef struct {
int volunteer_id;
struct Volunteer *next;
} Volunteer;
// 动态分配内存
Volunteer *create_queue(int size) {
Volunteer *queue = (Volunteer *)malloc(size * sizeof(Volunteer));
queue[0].volunteer_id = -1; // 初始化头节点
queue[0].next = NULL;
return queue;
}
// 插入操作
void insert(Volunteer **head, int id) {
Volunteer *new_node = (Volunteer *)malloc(sizeof(Volunteer));
new_node->volunteer_id = id;
new_node->next = *head;
*head = new_node;
}
// 删除操作
void delete(Volunteer **head, int id) {
if (*head == NULL || (*head)->volunteer_id != id)
return;
Volunteer *temp = *head;
*head = (*head)->next;
free(temp);
}
// 查找操作
int search(Volunteer *head, int id) {
Volunteer *current = head;
while (current != NULL && current->volunteer_id != id)
current = current->next;
return current ? current->volunteer_id : -1;
}
// 输出志愿者队列
void print_queue(Volunteer *head) {
Volunteer *current = head;
while (current != NULL) {
printf("志愿者ID: %d\n", current->volunteer_id);
current = current->next;
}
}
```
**2. 使用单链表实现:**
```c
typedef struct Node {
int volunteer_id;
struct Node *next;
} Node;
// 创建单链表
Node *create_linked_list() {
Node *list = (Node *)malloc(sizeof(Node));
list->volunteer_id = -1;
list->next = NULL;
return list;
}
// 插入操作
void insert_linkedList(Node **head, int id) {
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->volunteer_id = id;
new_node->next = *head;
*head = new_node;
}
// 删除操作
void delete_linkedList(Node **head, int id) {
if (*head == NULL || (*head)->volunteer_id != id)
return;
Node *temp = *head;
*head = (*head)->next;
free(temp);
}
// 查找操作
int search_linkedList(Node *head, int id) {
Node *current = head;
while (current != NULL && current->volunteer_id != id)
current = current->next;
return current ? current->volunteer_id : -1;
}
// 输出单链表
void print_linked_list(Node *head) {
Node *current = head;
while (current != NULL) {
printf("志愿者ID: %d\n", current->volunteer_id);
current = current->next;
}
}
```
现在你可以根据实际需求选择相应的实现,并对其进行插入、删除和查找操作。注意,在实际项目中,还需要处理内存管理错误和边界条件。
阅读全文