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)