用链表写飞机订票系统C语言
时间: 2023-07-25 12:44:06 浏览: 98
航空订票系统(C语言)(单链表)
5星 · 资源好评率100%
好的,以下是一个简单的飞机订票系统的链表实现的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Seat {
int seatNumber;
char* passengerName;
struct Seat* next;
} Seat;
typedef struct Flight {
char* flightNumber;
int totalSeats;
Seat* seatsList;
} Flight;
Flight* createFlight(char* flightNumber, int totalSeats) {
Flight* newFlight = (Flight*) malloc(sizeof(Flight));
newFlight->flightNumber = (char*) malloc(strlen(flightNumber) + 1);
strcpy(newFlight->flightNumber, flightNumber);
newFlight->totalSeats = totalSeats;
newFlight->seatsList = NULL;
return newFlight;
}
void reserveSeat(Flight* flight, int seatNumber, char* passengerName) {
if (seatNumber > flight->totalSeats) {
printf("The seat number is invalid.\n");
return;
}
Seat* currentSeat = flight->seatsList;
while (currentSeat != NULL) {
if (currentSeat->seatNumber == seatNumber) {
printf("The seat is already reserved.\n");
return;
}
currentSeat = currentSeat->next;
}
Seat* newSeat = (Seat*) malloc(sizeof(Seat));
newSeat->seatNumber = seatNumber;
newSeat->passengerName = (char*) malloc(strlen(passengerName) + 1);
strcpy(newSeat->passengerName, passengerName);
newSeat->next = flight->seatsList;
flight->seatsList = newSeat;
printf("Seat %d is reserved for %s.\n", seatNumber, passengerName);
}
void printFlight(Flight* flight) {
printf("Flight Number: %s\n", flight->flightNumber);
printf("Total Seats: %d\n", flight->totalSeats);
printf("Reserved Seats:\n");
Seat* currentSeat = flight->seatsList;
while (currentSeat != NULL) {
printf("%d: %s\n", currentSeat->seatNumber, currentSeat->passengerName);
currentSeat = currentSeat->next;
}
}
void deleteFlight(Flight* flight) {
Seat* currentSeat = flight->seatsList;
while (currentSeat != NULL) {
Seat* nextSeat = currentSeat->next;
free(currentSeat->passengerName);
free(currentSeat);
currentSeat = nextSeat;
}
free(flight->flightNumber);
free(flight);
}
int main() {
Flight* myFlight = createFlight("ABC123", 10);
reserveSeat(myFlight, 1, "John");
reserveSeat(myFlight, 2, "Mary");
reserveSeat(myFlight, 1, "Tom");
printFlight(myFlight);
deleteFlight(myFlight);
return 0;
}
```
在这个代码中,`Seat` 结构体代表一个座位,包含座位号 `seatNumber` 和乘客姓名 `passengerName`,以及指向下一个座位的指针 `next`。
`Flight` 结构体代表一个航班,包含航班号 `flightNumber`、总座位数 `totalSeats`,以及指向已预订座位链表的指针 `seatsList`。
在 `createFlight` 函数中,我们为航班动态分配内存,并将航班号、总座位数和已预订座位链表初始化为 `NULL`。
在 `reserveSeat` 函数中,我们首先检查座位号是否有效,然后遍历已预订座位链表,检查该座位是否已被预订。如果该座位已被预订,则输出错误信息;否则,为该座位动态分配内存,并将该座位加入已预订座位链表中。
在 `printFlight` 函数中,我们输出航班信息,包括航班号、总座位数和已预订座位信息。
在 `deleteFlight` 函数中,我们释放已预订座位链表和航班所占用的内存。
在 `main` 函数中,我们创建一个航班对象,预订几个座位,输出航班信息,然后释放航班对象和相关内存。
阅读全文