⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 freenodes.txt

📁 It is an ebook about data structures,mainly linked list
💻 TXT
字号:
  
   
Write a C program to free the nodes of a linked list. 

Discuss it!          



Before looking at the answer, try writing a simple C program (with a for loop) to do this. Quite a few people get this wrong. 


This is the wrong way to do it 


struct list *listptr, *nextptr; 
for(listptr = head; listptr != NULL; listptr = listptr->next) 
{ 
  free(listptr); 
} 


If you are thinking why the above piece of code is wrong, note that once you free the listptr node, you cannot do something like listptr = listptr->next!. Since listptr is already freed, using it to get listptr->next is illegal and can cause unpredictable results! 



This is the right way to do it 


struct list *listptr, *nextptr; 
for(listptr = head; listptr != NULL; listptr = nextptr) 
{ 
  nextptr = listptr->next; 
  free(listptr); 
} 
head = NULL; 


After doing this, make sure you also set the head pointer to NULL! 





 
 
 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -