用链表写一个航班订票系统
时间: 2023-05-22 15:05:45 浏览: 54
好的,以下是用链表实现的航班订票系统的代码:
typedef struct node {
char flight_number[10]; //航班号
int avail_seats; //可用座位数
struct node *next; //下一个节点
} Node;
Node *head = NULL; //头节点
//初始化节点
Node* init_node(char flight_number[10], int avail_seats) {
Node *new_node = (Node*)malloc(sizeof(Node));
strcpy(new_node->flight_number, flight_number);
new_node->avail_seats = avail_seats;
new_node->next = NULL;
return new_node;
}
//添加节点
void add_node(Node *new_node) {
Node *temp = head;
if (head == NULL) {
head = new_node;
return;
}
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = new_node;
}
//订票
void book_ticket(char flight_number[10]) {
Node *temp = head;
while (temp != NULL) {
if (strcmp(temp->flight_number, flight_number) == 0) {
if (temp->avail_seats > 0) {
temp->avail_seats --;
printf("预订成功!航班号:%s 可用座位数:%d\n", flight_number, temp->avail_seats);
} else {
printf("预订失败!航班号:%s 没有可用座位\n", flight_number);
}
return;
}
temp = temp->next;
}
printf("航班号:%s 不存在\n", flight_number);
}
//取消订票
void cancel_ticket(char flight_number[10]) {
Node *temp = head;
while (temp != NULL) {
if (strcmp(temp->flight_number, flight_number) == 0) {
temp->avail_seats ++;
printf("取消成功!航班号:%s 可用座位数:%d\n", flight_number, temp->avail_seats);
return;
}
temp = temp->next;
}
printf("航班号:%s 不存在\n", flight_number);
}
//打印所有航班
void print_flights() {
Node *temp = head;
while (temp != NULL) {
printf("航班号:%s 可用座位数:%d\n", temp->flight_number, temp->avail_seats);
temp = temp->next;
}
}
使用方法:首先调用 init_node 函数初始化一个节点,然后调用 add_node 函数将节点添加到链表中。如果需要订票或者取消订票,分别调用 book_ticket 和 cancel_ticket 函数,传入相应的航班号。如果需要打印所有航班信息,调用 print_flights 函数即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)