cout<<"chain total number:"<<c_header->length<<endl;
//正向访问
cout<<"正向访问"<<endl;
while(node_my !=NULL)
{
cout<<"node num:"<<node_my->num<<" data is:"<<*((int*)(node_my->data))<<endl;
node_my = node_my->next;
}
node_my = c_header->last_node;
//反向访问
cout<<"反向访问"<<endl;
while(node_my !=NULL)
{
cout<<"node num:"<<node_my->num<<" data is:"<<*((int*)(node_my->data))<<endl;
node_my = node_my->priv;
}
return 0;
}
int printchain_cube(my_chain* c_header)
{
if(c_header->frist_node ==NULL)
{
cout<<"NULL chain"<<endl;
return -1;
}
node* node_my = c_header->frist_node;
cout<<"chain total number:"<<c_header->length<<endl;
//正向访问
cout<<"正向访问"<<endl;
while(node_my !=NULL)
{
cout<<"node num:"<<node_my->num<<" data is:"<<((cube*)(node_my->data))->get_size()<<endl;
node_my = node_my->next;
}
node_my = c_header->last_node;
//反向访问
cout<<"反向访问"<<endl;
while(node_my !=NULL)
{
cout<<"node num:"<<node_my->num<<" data is:"<<((cube*)(node_my->data))->get_size()<<endl;
node_my = node_my->priv;
}
return 0;
}
int main()
{
cout<<"---int data chain:"<<endl;
{//3个测试int数据
my_chain* chain_int = new my_chain;//建立my_chain双向链表头
int i = 0;
for(i = 0;i<3;i++)
{
//最好使用malloc族函数使用free来释放void类型内存
int* data =(int*)calloc(1,sizeof(int));
//int* data = new int(i);
(*chain_int).addnode((void*)data);
}
printchain(chain_int);
#ifdef DEBUG
cout<<"释放内存"<<endl;
#endif
(*chain_int).freechain();
delete chain_int;
}
cout<<"---class data chain:"<<endl;
{//5个测试类数据
my_chain* chain_cube = new my_chain;//建立my_chain双向的链表头
int i = 0;
for(i = 0;i<5;i++)
{
//cube* data = new cube(i,i,i);
cube* data =(cube*)calloc(1,sizeof(cube));
(*data)=cube(i,i,i);//默认浅拷贝,这里无碍
(*chain_cube).addnode((void*)data);
}
printchain_cube(chain_cube);
#ifdef DEBUG
cout<<"释放内存"<<endl;
#endif
(*chain_cube).freechain();
delete chain_cube;
}
}
点击(此处)折叠或打开
测试结果:
---int data chain:
chain total number:3
正向访问
node num:1 data is:0
node num:2 data is:0
node num:3 data is:0
反向访问
node num:3 data is:0
node num:2 data is:0
node num:1 data is:0
释放内存
free node num:1
free node num:2
free node num:3
---class data chain:
chain total number:5
正向访问
node num:1 data is:0
node num:2 data is:1
node num:3 data is:8
node num:4 data is:27
node num:5 data is:64
反向访问
node num:5 data is:64
node num:4 data is:27
node num:3 data is:8
node num:2 data is:1
node num:1 data is:0
释放内存
free node num:1
free node num:2
free node num:3
free node num:4
free node num:5
内存泄露检测:
==4624==
==4624== HEAP SUMMARY:
==4624== in use at exit: 0 bytes in 0 blocks
==4624== total heap usage: 18 allocs, 18 frees, 392 bytes allocated
==4624==
==4624== All heap blocks were freed -- no leaks are possible
==4624==
==4624== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==4624== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)