Mọi người cho em hỏi là có cách nào khác để khi mình xóa Node hoặc thêm Node mình vẫn biết được kích thước của danh sách mà không cần sử dụng hàm “SizeOfList” không ạ . Cảm ơn mọi người nhiều
#include <iostream>
using namespace std ;
struct Node{
int data ;
Node *pNext ;
};
struct SingleList{
Node *pHead ;
int n ;
};
void init(SingleList *&list)
{
list->pHead = NULL ;
}
Node *CreateNode(int d)
{
Node *pNode = new Node ;
if(pNode!=NULL)
{
pNode->data = d ;
pNode->pNext=NULL ;
}
else
{
cout<<"Cap phat bo nho that bai\n" ;
}
return pNode ;
}
void InserLast(SingleList *&list,int d)
{
Node *pNode = CreateNode(d) ;
if(list->pHead==NULL)
{
list->pHead=pNode ;
}
else
{
Node *pTmp = list->pHead ;
while(pTmp->pNext!=NULL)
{
pTmp=pTmp->pNext ;
}
pTmp->pNext=pNode ;
}
}
int SizeOfList(SingleList *list)
{
int nsize=0 ;
Node *pTmp = list->pHead ;
if(list->pHead==NULL)
{
return 0 ;
}
else
{
while(pTmp!=NULL)
{
nsize++ ;
pTmp=pTmp->pNext ;
}
}
return nsize ;
}
int main()
{
SingleList *list = new SingleList ;
init(list) ;
InserLast(list,7) ;
InserLast(list,3) ;
InserLast(list,2) ;
int n =SizeOfList(list) ;
cout<<"Co "<<n<<" Node\n" ;
}