怎样用链表来实现c++车辆管理系统的程序设计
C++ 车辆管理系统 - 链表实现
使用链表来实现C++车辆管理系统可以有效管理车辆的动态数据。下面是一个详细的设计与实现步骤,包括定义车辆信息结构体,创建链表节点,添加、删除、搜索和显示车辆信息的函数。
1. 定义车辆信息结构体
cpp#include <iostream>
#include <string>
struct Vehicle {
std::string licensePlate;
std::string make;
std::string model;
int year;
};
2. 定义链表节点
cppstruct Node {
Vehicle vehicle;
Node* next;
};
3. 创建链表管理类
cppclass VehicleList {
private:
Node* head;
public:
VehicleList() : head(nullptr) {}
// 添加车辆
void addVehicle(const Vehicle& vehicle) {
Node* newNode = new Node{ vehicle, nullptr };
if (!head) {
head = newNode;
} else {
Node* temp = head;
while (temp->next) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 删除车辆
void removeVehicle(const std::string& licensePlate) {
if (!head) return;
if (head->vehicle.licensePlate == licensePlate) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* current = head;
Node* previous = nullptr;
while (current && current->vehicle.licensePlate != licensePlate) {
previous = current;
current = current->next;
}
if (current) {
previous->next = current->next;
delete current;
}
}
// 搜索车辆
Node* searchVehicle(const std::string& licensePlate) {
Node* current = head;
while (current) {
if (current->vehicle.licensePlate == licensePlate) {
return current;
}
current = current->next;
}
return nullptr;
}
// 显示所有车辆
void displayVehicles() {
Node* current = head;
while (current) {
std::cout << "License Plate: " << current->vehicle.licensePlate << "\n"
<< "Make: " << current->vehicle.make << "\n"
<< "Model: " << current->vehicle.model << "\n"
<< "Year: " << current->vehicle.year << "\n"
<< "--------------------------\n";
current = current->next;
}
}
// 释放内存
~VehicleList() {
Node* current = head;
while (current) {
Node* temp = current;
current = current->next;
delete temp;
}
}
};
4. 主程序示例
cppint main() {
VehicleList vehicleList;
// 添加车辆
Vehicle v1 = { "ABC123", "Toyota", "Camry", 2010 };
Vehicle v2 = { "XYZ789", "Honda", "Civic", 2015 };
Vehicle v3 = { "LMN456", "Ford", "Focus", 2018 };
vehicleList.addVehicle(v1);
vehicleList.addVehicle(v2);
vehicleList.addVehicle(v3);
// 显示所有车辆
std::cout << "所有车辆信息:\n";
vehicleList.displayVehicles();
// 搜索车辆
std::string searchPlate = "XYZ789";
Node* foundVehicle = vehicleList.searchVehicle(searchPlate);
if (foundVehicle) {
std::cout << "找到车辆:\n"
<< "License Plate: " << foundVehicle->vehicle.licensePlate << "\n"
<< "Make: " << foundVehicle->vehicle.make << "\n"
<< "Model: " << foundVehicle->vehicle.model << "\n"
<< "Year: " << foundVehicle->vehicle.year << "\n";
} else {
std::cout << "未找到车牌号为 " << searchPlate << " 的车辆。\n";
}
// 删除车辆
vehicleList.removeVehicle("ABC123");
// 显示所有车辆
std::cout << "删除车辆后所有车辆信息:\n";
vehicleList.displayVehicles();
return 0;
}
总结
通过上述步骤,我们实现了一个简单的车辆管理系统,使用链表来存储车辆信息。系统包括添加、删除、搜索和显示车辆信息的功能。链表的动态特性使得我们可以方便地管理不确定数量的车辆数据。
关键字
C++,车辆管理系统,链表,文件操作,数据存写,Vehicle结构体,Node结构体,链表管理类,添加车辆,删除车辆,搜索车辆,显示车辆信息。