![](/img/trans.png)
[英]How do I check whether the my linked list is empty in C++ in a function used for deleting nodes
[英]how to check if linked list is empty
我正在做一個項目,我需要將產品添加到鏈接列表中。 當我添加產品時,它還將初始值計為產品。 在我的代碼中,當我打印產品價格時,添加價格為20的產品“ aaaa”和價格為111的“ bbbb”,其價格為“ 0 20 111”。 值“ 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
鏈表不包含任何節點時為空。 通常,您通過指向列表頭(第一個節點)的指針訪問鏈接列表。 如果沒有節點,則頭指針為空,列表為空。
您似乎出於某種原因(可能是一項作業)編寫了自己的鏈接列表?
你很可能只是使Product* next
指向this
時候它是空的。 因此,如果next == this
則列表為空。 或者,如果列表的頭節點為null
則列表為空。
將來,我建議您將鏈接列表實現與Product
代碼分開。 您應該能夠擁有一個List<Product>
,而不是同時將Product
作為一個列表和其他東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.