线性表是最简单的数据组织形式,通过单向链表我们可以建立小表单存储一些简单的数据。
下面就来做一个仓储管理的练习:
Main函数已经给出:
那我们先定义好链表Goods类:
class Goods {
public:
Goods(int sW) {
singleWeight = sW;
totalWeight += singleWeight;//构造函数增上单重量
}
~Goods() {
totalWeight -= singleWeight;//析构函数减去单重量
}
int getSW() {
return singleWeight;
}
static int TotalWeight() {
return totalWeight;
}
Goods * next;
private:
static int totalWeight;//总重量
int singleWeight;//单货重量
};
再写买进卖出函数:
//买进
void purchase(Goods *& front, Goods *rear, int w) {
Goods *p = NULL;
if (!front) {
rear = new Goods(w);
front = rear;
return;
}
for (rear = front; rear; p = rear, rear = rear->next);//迭代至列尾
rear = new Goods(w);
p->next = rear;
}
//卖出
void sale(Goods *& front, Goods *rear) {
if (!front) {
cout << "库存已空" << endl;
return;
}
rear = front->next;
delete front;
front = rear;
}
然后多定义个遍历链表方法:
void showList(Goods * head) {
while (head) {
cout << head->getSW() << ends;
head = head->next;
}
cout << endl;
}
结果如下:
效果实现,目标达成!