特点:
1、动态内存分配,不需提前给定存储空间,非连续存储。
2、每个链表节点包含了两个阈,数据阈和指针阈,指针域存放节点间的地址联系。
3、类型可分为:单向、双向、循环、循环双向链表
应对场景:
频繁增添、删除元素
下面是一个用单链表完成购物车的增添、删减、打印操作的C++代码
#include"iostream"
#include"string"
using namespace std;
struct Product
{
string shopname;
float shopprice;
float shopquantity;
Product *next;
};
class Shoppingcart
{
private:
Product *head;
public:
// 构造函数
Shoppingcart():head(nullptr){};
// 析构函数
~Shoppingcart();
// 增加商品至购物车
void addproduct(const string & name, float price, float quantity);
// 从购物车删除商品
void deleteproduct(const string & name, float price, float quantity);
// 展示购物车的商品
void showshoppingcart();
};
void Shoppingcart::addproduct(const string & name, float price, float quantity)
{
Product *newproduct = new Product{name, price,quantity,nullptr};
// 判断购物车是否为空
if (head==nullptr)
{
head = newproduct;
}
else
{
// 使用的头插法,新节点在头部;尾插法需要先遍历到纬度再插入
newproduct->next = head;
head = newproduct;
}
// 添加到相应位置而不是单纯添加到末尾的代码没有写
}
void Shoppingcart:: deleteproduct(const string & name, float price, float quantity)
{
// 判断购物车是否为空
if (head == nullptr)
{
cout<<"failure to delect product, shoppingcart is empty"<<endl;
return;
}
// 查询是删除的商品是否存在
Product *previous = nullptr;
Product *current = head;
while (current!=nullptr && (current->shopname != name || current->shopprice != price || current->shopquantity != quantity))
{
previous = current;
current = current->next;
}
if (current == nullptr)
{
cout<<"The product do not exit"<<endl;
return;
}
if (previous == nullptr) // 第一个商品就是需要删除的商品,则previous为空
{
head = current->next;
}
else
{
previous->next = current->next;
}
delete current;
cout<<"The "<<name<<","<<price<<","<<quantity<<" had deleted"<<endl;
}
void Shoppingcart:: showshoppingcart()
{
cout<<" 购物车内存在以下商品: "<<endl;
Product *current = head;
while (current != nullptr)
{
cout<<current->shopname<<'\t'<<current->shopprice<<'\t'<<current->shopquantity<<'\t'<<current<<endl;
current = current->next;
}
cout<<"------------------------------"<<endl;
}
Shoppingcart::~Shoppingcart()
{
Product *current = head;
while (current != nullptr)
{
Product *temp = current;
current = current->next;
delete temp;
}
}
int main()
{
Shoppingcart sh;
int judgementvalue = 100;
while (judgementvalue)
{
cout<<"请选择功能:"<<endl;
cout<<" 1 查询"<<endl;
cout<<" 2 添加"<<endl;
cout<<" 3 删除"<<endl;
cout<<" 0 退出"<<endl;
cin>>judgementvalue;
switch (judgementvalue)
{
case 1:
sh.showshoppingcart();
break;
case 2:
{
string name;
float price,quantity;
cin>>name>>price>>quantity;
sh.addproduct(name,price,quantity);
break;
}
case 3:
{
string name;
float price,quantity;
cin>>name>>price>>quantity;
sh.deleteproduct(name, price, quantity);
break;
}
default:
break;
}
}
return 0;
}