使用链表模拟火车站售票系统。每个节点代表一名乘客,包含姓名、目的地、座位号等信息。用c语言,且代码可运行 功能要求: 乘客购票:将新乘客信息插入链表末尾。 乘客退票:根据姓名或座位号删除对应节点。 查询车票:根据姓名或目的地查找乘客信息。 显示所有乘客信息。
时间: 2024-12-28 08:39:47 浏览: 5
在C语言中,我们可以创建一个结构体表示乘客,然后定义一个单链表来存储乘客信息。这里是一个简单的实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Passenger {
char name[50];
char destination[50];
int seat_number;
} Passenger;
typedef struct Node {
Passenger info;
struct Node* next;
} Node;
// 创建新的乘客节点
Node* create_new_passenger(char* name, char* destination, int seat_number) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode != NULL) {
strncpy(newNode->info.name, name, sizeof(newNode->info.name) - 1);
strncpy(newNode->info.destination, destination, sizeof(newNode->info.destination) - 1);
newNode->info.seat_number = seat_number;
newNode->next = NULL;
}
return newNode;
}
// 插入乘客到链表尾部
void insert_passenger(Node** head, char* name, char* destination, int seat_number) {
Node* newNode = create_new_passenger(name, destination, seat_number);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 删除乘客节点(按名字或座位号)
Node* delete_passenger(Node* head, char* target_name, int target_seat_number) {
if (head == NULL) return head;
Node* current = head;
if (strcmp(current->info.name, target_name) == 0 || current->info.seat_number == target_seat_number) {
Node* temp = head;
head = head->next;
free(temp);
return head;
}
while (current->next != NULL) {
if (strcmp(current->next->info.name, target_name) == 0 || current->next->info.seat_number == target_seat_number) {
Node* temp = current->next;
current->next = current->next->next;
free(temp);
return head;
}
current = current->next;
}
return head;
}
// 查询乘客信息
Passenger* find_passenger(Node* head, char* query_name, int query_seat_number) {
if (head == NULL) return NULL;
Node* current = head;
while (current != NULL) {
if (strcmp(current->info.name, query_name) == 0 && current->info.seat_number == query_seat_number) {
return ¤t->info;
}
current = current->next;
}
return NULL;
}
// 显示所有乘客信息
void display_all_passengers(Node* head) {
if (head == NULL) {
printf("No passengers.\n");
} else {
Node* current = head;
while (current != NULL) {
printf("Name: %s, Destination: %s, Seat Number: %d\n", current->info.name, current->info.destination, current->info.seat_number);
current = current->next;
}
}
}
int main() {
Node* head = NULL;
// 示例操作
insert_passenger(&head, "张三", "北京", 101);
insert_passenger(&head, "李四", "上海", 202);
display_all_passengers(head);
// 操作示例
Passenger* found_info = find_passenger(head, "张三", 101);
if (found_info != NULL) {
printf("Found passenger: Name: %s, Seat Number: %d\n", found_info->name, found_info->seat_number);
} else {
printf("Passenger not found.\n");
}
head = delete_passenger(head, "张三", 101);
display_all_passengers(head);
return 0;
}
```
这个程序实现了基本的火车站售票系统功能,包括添加乘客、查询、删除以及显示乘客信息。你可以根据需要调整主函数中的操作。
阅读全文