C++实现购物车管理系统数据结构
时间: 2023-07-08 19:50:48 浏览: 86
购物车管理系统可以使用链表数据结构来实现。每个节点表示一个商品,包含商品信息和指向下一个商品的指针。具体实现可以参考以下代码:
```c++
#include <iostream>
#include <string>
using namespace std;
// 商品类
class Commodity {
public:
string name; // 商品名称
double price; // 商品价格
int count; // 商品数量
Commodity* next; // 指向下一个商品的指针
// 构造函数
Commodity(string name, double price, int count):
name(name), price(price), count(count), next(NULL) {}
};
// 购物车类
class ShoppingCart {
public:
Commodity* head; // 指向购物车中第一个商品的指针
// 构造函数
ShoppingCart(): head(NULL) {}
// 添加商品
void addCommodity(string name, double price, int count) {
Commodity* commodity = new Commodity(name, price, count);
commodity->next = head;
head = commodity;
}
// 删除商品
void removeCommodity(string name) {
if (head == NULL) {
return;
}
if (head->name == name) {
head = head->next;
return;
}
Commodity* cur = head;
while (cur->next != NULL && cur->next->name != name) {
cur = cur->next;
}
if (cur->next != NULL) {
Commodity* temp = cur->next;
cur->next = temp->next;
delete temp;
}
}
// 显示购物车中所有商品
void display() {
Commodity* cur = head;
while (cur != NULL) {
cout << cur->name << " " << cur->price << " " << cur->count << endl;
cur = cur->next;
}
}
};
int main() {
ShoppingCart cart;
cart.addCommodity("apple", 5.0, 2);
cart.addCommodity("banana", 3.0, 5);
cart.addCommodity("orange", 4.0, 3);
cart.removeCommodity("banana");
cart.display();
return 0;
}
```
上面的代码使用链表实现了购物车管理系统。其中,`Commodity`类表示商品,包含了商品的名称、价格、数量和指向下一个商品的指针。`ShoppingCart`类表示购物车,包含了指向购物车中第一个商品的指针,提供了添加、删除和显示商品的方法。在`main`函数中,我们可以看到如何使用购物车管理系统来添加、删除和显示商品。