我正在制作一个项目,我需要将产品添加到链接列表中。当我添加产品时,它也将初始化值计为产品。在我的代码中,当我打印产品的价格为“0 20 111”时,我将价格为20的产品“aaaa”和价格为111的“bbbb”相加。值“0”是初始化的值,我不保存它的程序。我需要找出列表是否为空,如果是,则将第一项添加到列表中。我该怎么做?
这是我的代码:如何检查链表是否为空
main.cpp中:
#include <iostream>
//#include <string>
using namespace std;
#include "List.h"
int main(){
int option;
Product productsListHead;
productsListHead.printProducts(&productsListHead);
productsListHead.addProduct(&productsListHead,1,"aaaa",20);
productsListHead.printProducts(&productsListHead);
productsListHead.addProduct(&productsListHead,2,"bbbb",111);
if(option==1){
productsListHead.printProducts(&productsListHead);
}
return 1;
}
List.cpp:
#include <iostream>
#include <string>
#include <cstdlib>
#include "List.h"
using namespace std;
void Product::addProduct(Product* head,int id,char* name, int price){
Product* TheNewProduct = new Product;
TheNewProduct->setNext(NULL);
TheNewProduct->setId(id);
TheNewProduct->setName(name);
TheNewProduct->setPrice(price);
Product *tmp = head;
if (tmp != NULL)
{
cout<<"the list is not empty"<<endl;
// Nodes already present in the list
// Parse to end of list
while (tmp->Next() != NULL) {
tmp = tmp->Next();
}
// Point the last node to the new node
tmp->setNext(TheNewProduct);
}
else
{
cout<<"the list is empty"<<endl;
// First node in the list
head = TheNewProduct;
}
}
void Product::printProducts(Product* head)
{
//Product* tmp=head;
for (; head; head = head->Next())
{
cout << head->Price() << endl;
}
}
Product::Product(){
next=NULL;
id=0;
name="";
price=0;
}
头文件 - > List.h:
#pragma once
#ifndef LIST_H
#define LIST_H
//#include <string>
using namespace std;
class Product{
private:
int id;
char* name;
int price;
Product* next;
public:
Product();//constructor
//Product* Next(){return next;};
//~Products();
Product* Next() { return next; };
int Id(){return id;};
char* Name(){return name;};
int Price(){return price;};
void setId(int new_id){id=new_id;};
void setPrice(int new_price){price=new_price;};
void setNext(Product* new_next){next=new_next;};
void setName(char* new_name){name=new_name;};
void printProducts(Product* head);
void addProduct(Product* head,int id, char* name, int price);
//void updateNameProduct(int id, char* oldName, char* newName);
};
#endif
你刚才问我们如何使用*你自己的*代码? –
我假设这是一个学习项目,这就是你不使用'std :: list'的原因? –
如果这是班级作业,请问你的老师。如果这是您自己的代码,请使用std :: list(或类似的东西),而不是滚动您自己的代码。 –